Challenge - Check for Palindromes

Hi FCCers,

I’m now at the “check for palindromes”. below is my solution and it works. but I wonder if the code can be improved so it can work better? Also I’m interested to know how you solve this problem?

function palindrome(str) {
  var newStr = str.replace(/[^A-Za-z0-9]/gi, "").toLowerCase();
  var result = newStr.split("").reverse().join("");
  if(result === newStr){
    return true;
  } else{
    return false;
  }
  
 
}

palindrome("eye");

I searched and found that string.replace(/[^9-Za-z0-9]/g, “”) can be used to remove all non-alphanumeric chars. however, I don’t understand why [^9-Za-z0-9] removes non-alphanumeric chars. can someone please help me to understand?

Thanks!

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

This block:

if (result === newStr) {
  return true;
} else {
  return false;
}

is equivalent to

return result === newStr;

You can replace

str.replace(/[^A-Za-z0-9]/gi, "").toLowerCase();

with

str.toLowerCase().replace(/[^a-z0-9]/g, ""); // shorter regex for sanity
3 Likes

My code was similar to what you did! Great job!

      function palindrome(str) {
      //use a regular expression to find unusables & make lowercase
      var newStr = str.replace(/\W+/g, "").replace(/_/g, "").toLowerCase();
      
      //reverse the string
      var newArray = newStr.split('');
      newArray.reverse();
      var reversed = newArray.join('');
      
      //test if the palindrome is there or not
      return newStr == reversed;
      
    }

    palindrome('_eye');

A quick run down of the comparison operator I used;

To test if something is true / false, you can simply return the comparison operator shown below

==

or

===

These both operate identically but the triple comparison operator will ignore any type conversion that may need to be done. For example, if you where to compare

0 == '0'

this would return true. The double comparison will convert the number to a string in order to compare the two. And since the string ‘0’ and ‘0’ are the same, it returns true. The triple comparison will return false because the two are not the same type. A string is not a number.

Hi thanks for pointing out the flaws.
regarding the regex, /[^a-z0-9]g/ can be used to remove all non-alphanumeric chars? how is it different to (/[^A-Za-z0-9]/gi that I used?
thanks!

Hi, I just tried replacing str.replace(/[^A-Za-z0-9]/gi, “”).toLowerCase(); with str.toLowerCase().replace(/[^a-z0-9]g/, “”); however, it didn’t pass the tests. anything wrong?

Oops, my bad. The g should be after the slash: /[^a-z0-9]/g

/[^a-z0-9]/g will only work if you lowercased the string first. There are no uppercase letters to look for then.

If you add the i flag at the end of your regex (like you did in /[^A-Za-z0-9]/gi, it will ignore capitalization, and the A-Z part becomes unnecessary.

Great! Thanks for your help! :smile: