function palindrome(str) {
var strReverse=str.toLowerCase().replace(/\W+/g,'').split('').reverse().join('');
if(strReverse===str)
return true;
else
return false;
}
This program should check for the following palindromes:
palindrome("eye") should return true.
palindrome("race car") should return true.
palindrome("not a palindrome") should return false.
palindrome("A man, a plan, a canal. Panama") should return true.
palindrome("never odd or even") should return true.
palindrome("nope") should return false.
palindrome("almostomla") should return false.
palindrome("My age is 0, 0 si ega ym.") should return true.
palindrome("1 eye for of 1 eye.") should return false.
palindrome("0_0 (: /-\ :) 0-0") should return true.
But its not working for the multi string lines. I think its because of the RegEx
but I cannot seem to find what is exactly wrong.
Try this function
function palindrome(str) {
str=str.toLowerCase().replace(/[^A-Za-z]+/g, '');
var strReverse = str.split('').reverse().join('');
if(strReverse===str)
return true;
else
return false;
}
Issue in your code was that when you were comparing the strReverse
with str
, strReverse
was formatted but str
was not. Like you didn't remove special characters and spaces and numbers from str, you didn't made it lowercase
etc.