Check For Palindromes Question

The first code does not work, the second does. For the first, I get the typeError: str.split() is not a function. Will someone help me understand the difference between the two codes?

function palindrome(str) {
  var re=/[\W_]/g;
  var lower=str.split("").toLowerCase().replace(re,"");
  var rvrs=lower.reverse().join("");
  return lower===rvrs;
}
palindrome("eye");
function palindrome(str) {
  var re = /[\W_]/g;
  var lowRegStr = str.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  return reverseStr === lowRegStr;
}
palindrome("A man, a plan, a canal. Panama");

Hi @bshelt

The error is because srt.split('') returns an array, so when you chain .toLowerCase() it returns the error because toLower is a string function, not an array function. You probably want to switch them around like: str.toLowerCase().split("")

1 Like

Thanks @joesmith100
I didn’t take into account that both .toLowerCase() and .replace() are both string methods.

1 Like

That is the reason why you have to be very careful when chaining methods :slight_smile:

1 Like