I borrowed a book that has the following assignment: Create a script with a function isPalindrome(x) which returns true if and only if x is a string that is a palindrome, that is, it reads the same forward an backwards: A man, a plan, a canal, Panama! Can somebody help me with this?
One way: function isPalindrome(strX) { var arrX = strX.split(""); //creates an array of the characters within strX arrX.reverse(); //reverse the array var Xrts = arrX.join(""); //join it back together, creating the reverse of strX return(strX == Xrts); //return true if they match, false if they don't } Code (markup):
Or to improve on this we need to remove all punctuation and spaces using regex, and convert to lower-case: function isPalindrome(strX) { strX = strX.replace(/[^a-zA-Z0-9]+/g,"").toLowerCase(); //leave only alphanumeric chararacters, and convert to lower case. return(strX == strX.split("").reverse().join("")); //same as before but made into one line. } alert(isPalindrome("A man, a plan, a canal, Panama! ")); Code (markup):
strX.split("").reverse().join("") << this line may seem to strange to you but you can do this... strX <<is a string object .split("") <<is a function of a string, that splits the the string into an array... .reverse() <<is a function of an array (which we now have because we split the string) .join() <<.join() is basically the opposite of .split(), it joins the array back into a string.. So we have gone from string, to array, and back to string all in one line..