FCC: Palindrome Checker

Hello everyone. I just completed my first JavaScript Algorithms and Data Structures Project and here is the solution:


function palindrome(str) {

    // Declare a regex to return only alphanumeric characters
  let strRegex = /[A-Za-z0-9]/;

  // split the string into an array of individual characters
  let splitStr = str.split('').filter((a) => a.match(strRegex)).map((a) => a.toLowerCase());

 /* Declare a variable to hold the revised str containing only alphanumeric characters that are not reversed */
  let newStr = splitStr.join('');
  
  // Run a for loop to iterate through the splitStr Array
  let reversedStr = '';
  for (let i = 0; i < newStr.length; i++) {
    reversedStr += splitStr.pop();
  }
  
  // Check if the newStr is equal to reversedStr.
  // if so return true (it is a palindrome)
  //else return false (it is not a palindrome)

  return newStr === reversedStr;
}

console.log(palindrome("_eye"));

Now I want to understand something. Why is it that when I use this shortened way of representing alphanumeric characters; /\w/ am failing to pass the challenge, but when i use the longer way; /[A-Za-z0-9]/ am passing the challenge?

My guess is it’s the underscore. \w matches any letter, digit or underscore. It is equivalent to [a-zA-Z0-9_].

1 Like

Oh that must be it because when I used /\w/ for my regex it was not removing the underscore. This puzzled me a lot. Not until I decided to use the longer regex /[A-Za-z0-9]/. My thought was these two expressions are one and same.
Thank you Ariel Leslie.

I’m glad I could help. Happy coding!

1 Like