Understanding the palindrome code with the logic of split and reverse - javascript

I am trying to write a palindrome code, so I am using the split and reverse methods. Is my below logic correct? Can I directly use the reverse method instead of giving split and then reverse?
If I give == it prints palindrome where as if I give === it prints not palindrome. I am a beginner in JS and I am trying to learn.
var actualWord = "madam"
var splittedWord = actualWord.split();
console.log("splittedWord---->" + splittedWord);
var reversedWord = splittedWord.reverse();
console.log("reversedWord---->" + reversedWord);
console.log("boolean" + reversedWord === actualWord);
if (reversedWord === actualWord) {
console.log("palindrome");
} else {
console.log("not palindrome")
}

Your logic is flawed as split() with no parameter to split by returns the original word, which then means that reverse() has no effect as you're working on a single element array. You are also attempting to check arrays for equality, which will not work.
To do what you require you need to split by '' to generate a character array which you can then reverse() and join() back together to invert the characters of the word. Then you can compare the words to discover if the original was a palindrome. Try this:
var actualWord = "madam"
var reverseWord = actualWord.split('').reverse().join('');
console.log(actualWord, reverseWord);
if (actualWord === reverseWord) {
console.log(actualWord + " IS a palindrome");
} else {
console.log(actualWord + " IS NOT a palindrome")
}
Working example
Taking this a step further you could extract the logic to it's own function and make the string comparison case-insensitive:
console.log('madam', isPalindrome('madam'));
console.log('madame', isPalindrome('madame'));
console.log('raceCAR', isPalindrome('raceCAR'));
function isPalindrome(word) {
var reverseWord = word.split('').reverse().join('');
return word.toLowerCase() === reverseWord.toLowerCase();
}
Example fiddle

Several things needed to make your code correct:
Split the words using .split("") not .split()
Create strings from the arrays using .join("")
Put parentheses around the comparator in your "boolean" line, otherwise the "+" will be performed before the "==="
var actualWord = "madam";
var splittedWord = actualWord.split("");
log("splittedWord---->" + splittedWord.join(""));
var reversedWord = splittedWord.reverse();
log("reversedWord---->" + reversedWord.join(""));
log("boolean---->" + (reversedWord.join("") === actualWord));
if (reversedWord.join("") === actualWord) {
log("palindrome");
} else {
log("not palindrome")
}
function log(str) {
document.body.appendChild(document.createElement("p")).innerHTML = str;
}

The == operator will compare for equality after doing any necessary
type conversions. The === operator will not do the conversion, so if
two values are not the same type === will simply return false. It's
this case where === will be faster, and may return a different result
than ==. In all other cases performance will be the same.
e.g.-
"1" == 1
true
"1" === 1
false
in your case, reversedWord is an array but actualWord is string, hence you get false when using ===, but when you use == JS does the necessary type conversion for you and you get true.

You have to call the split function before the reverse function because you are referring to a string and not an array.

Related

javascript program to check if a string is palindromes not returning false

I wrote this bit of code a a part of an exercise to check weather or not a string is palindromes. They program is working correctly in terms of checking the string but it does not return false when the string is not palindromes. What am I doing wrong? thanks
//convert the string to array
var stringArr = [ ];
var bool;
function palindrome(str) {
// make lowercase
var lowerCase = str.toLowerCase();
//remove numbers, special characters, and white spaces
var noNumbers = lowerCase.replace(/[0-9]/g, '');
var noSpecials = noNumbers.replace(/\W+/g, " ");
var finalString = noSpecials.replace(/\s/g, '');
stringArr = finalString.split("");
if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) {
bool = true;
}
else {
bool= false;
}
return bool;
}
function frontToBack (a,b) {return a-b;}
function backToFront (a,b) {return b-a;}
palindrome("eye");
if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) { is your problem.
In JavaScript, the sort method updates the value of the variable you are sorting. So in your comparison, once both sort's have run, both end up with the same value (since the second sort, effectively overrides the first).
For example.
var a = [1,7,3];
a.sort();
console.log(a); // will print 1,3,7
Edit: had a quick test, I think eavidan's suggestion is probably the best one.
Edit2: Just put together a quick version of a hopefully working palindrome function :)
function palindrome(str) { return str.split("").reverse().join("") == str;}
It is because string subtraction yields NaN, which means both sorted arrays are the same as the original.
Even if you did convert to ASCII coding, you sort the entire string, then for instance the string abba would be sorted front to back as aabb and back to front as bbaa. (edit: and also what Carl wrote about sort changing the original array. Still - sort is not the way to go here)
What you should do is just reverse the string (using reverse on the array) and compare.
You might do as follows;
var isPalindrome = s => { var t = s.toLowerCase()
.replace(/\s+/g,"");
return [].slice.call(t)
.reverse()
.every((b,i) => b === t[i]);
};
console.log(isPalindrome("Was it a car or a cat I saw"));
console.log(isPalindrome("This is not a palindrome"));
function pal()
{
var x=document.getElementById("a").value;
//input String
var y="";
//blank String
for (i=x.length-1;i>=0;i--)
//string run from backward
{
y=y+x[i];
//store string last to first one by one in blank string
}
if(x==y)
//compare blank and original string equal or not
{
console.log("Palindrome");
}
else
{
console.log("Not Palindrome ");
}
}

Number and Alphabet Separation in a String

I have String variables in Javascript like :
var houseNo = "62A"; var cabinNo = "5BC";
I need to fetch out the Integers and the Alphabets separate from the string where number of occurrences of each can be any number of times.
Need help to do it in the best possible way, be it through lodash or any other prototype method.
Referred to this but left in vain as don't want it through RegEx.
something like :
function decompose(string){
for(var i=0;i<string.length;i++){
if(parseInt(string[i])){ // if the char is a number?
// do whatever you want
}else{
// it's a character
}
}
}
The parseInt() function return the number of a giver char. If it is not a number, it returns NaN (not a number). if(parsInt(char)) return false if it's a char, true if it's a number
Try this:
var houseNo = "62A";
foreach(char a in houseNo)
{
if(a > 48 && a < 57)
{
/*it's a number*/
}
else
{
/*it's a letter*/
}
}
You can apply it on every string and determine what you want to do with each number or letter.
var test = "a3434dasds3432s2"
var myString = test.split("").filter(function(v) {return isNaN(v)}).join("")
var myNumber = parseInt(test.split("").filter(function(v) {return !isNaN(v)}).join(""))
best to use regex really though.

Failing test as a string

I am running through some exercises and run into this on codewars. Its a simple exercise with Instructions to create a function called shortcut to remove all the lowercase vowels in a given string.
Examples:
shortcut("codewars") // --> cdwrs
shortcut("goodbye") // --> gdby
I am newbie so I thought up this solution. but it doesn't work and I have no idea why
function shortcut(string){
// create an array of individual characters
var stage1 = string.split('');
// loop through array and remove the unneeded characters
for (i = string.length-1; i >= 0; i--) {
if (stage1[i] === "a"||
stage1[i] === "e"||
stage1[i] === "i"||
stage1[i] === "o"||
stage1[i] === "u") {
stage1.splice(i,1)
;}
};
// turn the array back into a string
string = stage1.join('');
return shortcut;
}
My gut is telling me that it will probably something to like split and join not creating "true" array's and strings.
I did it at first with a regex to make it a little more reusable but that was a nightmare. I would be happy to take suggestions on other methods of acheiving the same thing.
You are returning the function itself, instead of returning string
Using regex:
var str = 'codewars';
var regex = /[aeiou]/g;
var result = str.replace(regex, '');
document.write(result);
if interested in Regular Expression ;)
function shortcut(str) {
return str.replace(/[aeiou]/g, "");
}

How can i write function called validate(z) which takes a string as argument & return true if contain 1 "#" symbol & at least 1 "." & false otherwise

I have just started to learn functions and am finding it quite difficult.
I have learnt a few different functions but I haven't ever done a function like this.
How do I write a function called validate(z) which takes a string as an argument and returns true if it contains one # symbol and at least one dot . and false otherwise.
E.g. if z = "stack#overflow.co.uk" the function will return true.
Regex seems like a lot of overkill for such a simple requirement. I'd go with something like this
function validate(z) {
var hasDots = z.indexOf('.') !== -1,
firstAt = z.indexOf('#'),
lastAt = z.lastIndexOf('#');
return hasDots && firstAt !== -1 && firstAt === lastAt;
}
It sounds like what you're looking for is an email validation function. These are a lot more tricky to write than you may expect. You have to validate length as well as format. Here's one that's worked well for me in all of my implementations using a (quite complicated) regex statement.
function validateEmail(v) {
var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return (v.match(r) == null) ? false : true;
}
You can use regex.
function validate(z) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(z);
}
For the dot, use indexOf to search for the character in the input:
function contains(z, c) {
return z.indexOf(c) !== -1;
}
To check for a single #, you could say
function contains_one(z, c) {
var first = z.indexOf(c);
var last = z.lastIndexOf(c);
return first !== -1 && first == last;
}
function validate(z) {
return contains_one(z, '#') && contains(z, '.');
}
If you prefer to use regexp:
function validate(z) {
return /^[^#]*#[^#]*\.[^#]*$/.test(z);
}
This says asks for a sequence of non-at-signs, followed by an at-sign, followed by a sequence of non-at-signs, followed by a dot, followed by a sequence of non at signs. You may want to tweak this. For instance, it insists that the dot be to the right of the at sign. Also, it allows the dot to come immediately after the at-sign, or immediately at the end of the input.

Javascript, string, RegEx, if and else if, console.log different output

I want to output a string's vowels in order, so I decided to use RegEx to do it.
However, when I put the expression in different position in (if and else if), the output is different for the same expression. Could anyone explain?
function ordered_vowel_word(str) {
if(str.match(/[aeiou]{1,}/g) !== ""){
var arr = str.match(/[aeiou]{1,}/g);
console.log(arr);
}
else
console.log(str);
}
ordered_vowel_word("bcg");
ordered_vowel_word("eebbscao");
/* The Output */
ordered_vowel_word("bcg");
==> null
ordered_vowel_word("eebbscao");
==> ["ee", "ao"]
But if I restructure the expression,
function ordered_vowel_word(str) {
if(str.match(/[^aeiou]/) !== "")
console.log(str);
else if(str.match(/[aeiou]{1,}/g) !== ""){
var arr = str.match(/[aeiou]{1,}/g);
console.log(arr);
}
}
The output will be
ordered_vowel_word("bcg");
==> bgv
ordered_vowel_word("eebbscao");
==> eebbscao
Take note that string.match returns an array if there is at least one match, and it returns null if there is no match.
What I think you want is :
if(str.match(/[aeiou]{1,}/g) == null){ // no matches
or
if(str.match(/[aeiou]{1,}/g) != null){ //has a match
As for the sorting, you have to do process the array you get with str.match.
Check out this SO answer for sorting arrays. Yes, you can use > and < operators for characters.
The return value of str.match the way you are using it is an array containing the matches when it matches. Also, it is not an empty string when there are no matches... it is actually null.
Try changing what you are testing for in your if condition to this:
str.match(/[aeiou]{1,}/g) !== null)

Categories