Why are there extra spaces in my split array?

Should print out yes but it doesn’t.

function palindrome(str) {
  console.log(str.toLowerCase().split(/[_\W\s]/g).reverse().join(" "))
  console.log(str.toLowerCase().split(/[_\W\s]/g).join(" "))
  if(str.toLowerCase().split(/[_\W\s]/g).reverse().join(" ") === str.toLowerCase().split(/[_\W\s]/g).join(" ")){
    console.log("yes"); 
  }
  
  return true;
}



// palindrome("RaceCar");
// palindrome("race Car");
palindrome("A man, a plan, a canal. Panama"); 

Whenever confused, it often helps to break down your function chain into smaller bits and see what they output individually.
Your regex /[_\W\s]/g matches single characters at a time, so what happens if it meets consecutive matches like ', '?

console.log(str.toLowerCase().split([_\W\s]/g) gives us [ 'a', 'man', '', 'a', 'plan', '', 'a', 'canal', '', 'panama' ].

It makes sense, your regex will split another time between the ',' and the ' ', creating empty strings. Then when you join them back up, it creates extra spaces.

Yes I solved it by adding + at the end of regex. Now the problem I’m finding is that .reverse() only reverses the elements in the .split() array and not the individual strings. Unless I did something like this:

console.log(str.toLowerCase().split(/[_\W\s]+/g).join("").split("").reverse().join(""))

but I imagine it’s frowned upon because I am repeating myself.

You are correct, reverse() only works on arrays.

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