Palindrome checker - test for \w does not work

Tell us what’s happening:

I am trying to solve the palindrome checker with just a for loop; I have not yet completed all the Functional Programming Challenges, but I would like to try with what I have covered so far and later revisit this challenge and redo it with higher-order functions.

My plan is the following:

  1. convert str to lowercase and then to an array with split(), and save the new array to a variable arr;
  2. create a new, empty array newArr to store alpha-numeric characters from arr;
  3. iterate over each element of arr and if it is alpha-numeric, push it to newArr;
  4. reverse newArr with a reverse for loop and push() and compare it with newArr;

Right now I am stuck at 3. The test does not seem to be working and after the loop newArr is just [] [] []. But why?

Your code so far


function palindrome(str) {
let arr = str.toLowerCase().split(""); // convert str to lowercase and to an array
let newArr = []; // create an empty array to store filtered alphanumerical characters
let test = /\w/; // set up test for alphanumeric characters
// test whether each character in the array is an alphanumerical character
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === test) {
  // if it is, push it to the newArr
    newArr.push(arr[i]);
  }
  // newArr logs [] [] [] - why?
  console.log(newArr);
}
return true;
}



palindrome("eye");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.

Challenge: Palindrome Checker

Link to the challenge:

Take a closer look at the way you are checking if letter match the required pattern, and consider whether that’s the proper way to check if string matches pattern.

1 Like

Thank you, I was able to solve it thanks to your hint. It’s probably not the prettiest code you’ve seen but it works, and as I said I’ll come back to it after I’ve finished functional programming.

My solution:

function palindrome(str) {
  let arr = str.toLowerCase().split("");
  let newArr = [];
  let revArr = [];
  let testCase = /[0-9a-z]/;
  for (let character in arr) {
    if (testCase.test(arr[character])) {
      newArr.push(arr[character]);
    }
  }
  for (let i = newArr.length - 1; i >= 0; i--) {
      revArr.push(newArr[i]);
  }
  return newArr.join("") === revArr.join("");
}