Palindrome Program Avoiding Spaces, Punctuation In Javascript
I'm trying to make a palindrome program using javascript that will show if a string is palindrome or not by TRUE or FALSE even if the string has punctuation and spaces(ex- madam, i
Solution 1:
Within the "for" clause, replace "Math.floor(finalstring/2)" by "Math.floor(len/2)"
Also, you might want to improve your punctuation removal so that it also removes apostrophes, for instance.
So your code would become the following:
functionisPalindrome (str) {
var nopunctuation = str.replace(/\W/g,"");
var nospaces = nopunctuation.replace(/\s/g,"");
var finalstring = nospaces;
var len = finalstring.length;
for ( var i = 0; i < Math.floor(len/2); i++ ) {
if (finalstring[i] !== finalstring[len - 1 - i]) {
returnfalse;
}
}
returntrue;
}
Post a Comment for "Palindrome Program Avoiding Spaces, Punctuation In Javascript"