Book assignment question

Discussion in 'JavaScript' started by Maurovz, Dec 3, 2009.

  1. #1
    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?
     
    Maurovz, Dec 3, 2009 IP
  2. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    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):
     
    camjohnson95, Dec 3, 2009 IP
  3. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #3
    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):
     
    Last edited: Dec 3, 2009
    camjohnson95, Dec 3, 2009 IP
  4. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #4
    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..
     
    camjohnson95, Dec 3, 2009 IP