JavaScript Algorithms and Data Structures Projects - Palindrome Checker

Tell us what’s happening:
Hi Guys! I am trying to solve the first JS project which is a Palindrome Checker. I figured out how to do all of this stuff BUT one issue is still driving me crazy.

I try to find all special characters with a regex while i loop a char array of the parameter. While testing this loop i figured out that if there is a second special character right after another the second one won’t be matched. Could someone explain plese?

Your code so far

function palindrome(str) {
  
  let input = str.toUpperCase();
  let charArray = [...input];
  let reverseCharArray = [...charArray].reverse("");;
  let reverseInput = reverseCharArray.join("");
  let regex = /[\W_]/gm;
  let cleanCharArray = [];
  
 


  for(let i = 0; i < charArray.length; i++){
    if( !regex.test(charArray[i])){
      cleanCharArray.push(charArray[i])
    }   
  }

  return cleanCharArray;
 


  
  
  
  
}


console.log(palindrome("._d'dad#ada*d.aw.."));

Your browser information:

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

Challenge: JavaScript Algorithms and Data Structures Projects - Palindrome Checker

Link to the challenge:

1 Like

Your issue is being caused by a quirk in how regex objects work when using the test function. When you use the global flag /g, the regex object keeps track of what index it last found a match at and uses that value the next time it looks for a match.

You can see this in action by adding console.log(regex.lastIndex) to the first line in your for loop.

Take out the global flag and your code will work. You can also use string.match(/\W_/) instead of regex.test().

2 Likes

Well it was not my question I asked and the type of code you saw was just for test and debugging. I finished it this way

function palindrome(str) {
  
  let input = str.toUpperCase();
  let charArray = [...input]
  let cleanCharArray = []; 
  let regex = /[\W_]/m;

  for(let i = 0; i < charArray.length; i++){
    if( !regex.test(charArray[i])){
      cleanCharArray.push(charArray[i])
    }   
  }

  let reverseCharArray = [...cleanCharArray].reverse("");
  let reverseInput = reverseCharArray.join("");
  let cleanInput = cleanCharArray.join("");

  if(cleanInput === reverseInput){
    return true;
  }
  else if(cleanInput != reverseInput){
    return false;
  }
}
console.log(palindrome("five|\_/|four"));
type or paste code here

We have blurred this solution so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.