If you compare the 2 pieces of code, they’re actually a fair bit different than just using ‘==’ and ‘===’.
FYI the triple equals checks value AND type, so:
5 == '5' // true
5 === '5' // false
Anyway, the if you compact the first piece of code to be similar to the second, you’ll see what I mean.
// First piece of code
return str ==
str.replace(/[\W_]/g, "").toLowerCase().split("").reverse().join("")
// Second piece of code
return str.replace(/[\W_]/g, "").toLowerCase() ===
str.replace(/[\W_]/g, "").toLowerCase().split("").reverse().join("");
The first piece of code isn’t removing the non-alphanumeric characters, nor making them all lower case. That’s why it’s not behaving the same. In either instance, using == / === isn’t making a difference, although it’s always best practice to use ===.
I still don’t understand. Unless I’m missing the logic, the implicit meaning in “str == str.replace…” is “if the original str is equivalent to str.replace…, return true” - I don’t see why actually making those changes to the original string is necessary?
I’m coming from Python, which behaves differently, so maybe that’s why. This is a similar function (minus for the reg ex) in Python, which works fine:
A palindrome is a word or sentence that’s spelled the same way both forward and backward, ignoring punctuation, case, and spacing. Note
You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.
Let’s take 'eye_'
When you do str == str.replace... you are comparing eye_ with eye.
It’s not really a difference in the languages, I think you’re misunderstanding the challenge itself. As @jenovs said, you need to remove all the non-alpha characters BEFORE you check to see if it’s a palindrome. So what you’re really meant to do is check a modified version (non-alphas removed and lower cased) of the original string with it reversed, The 2nd piece of code does just that.
Hello!
I have an issue with my code, maybe someone can help. When I return reverseStr I get as result :eye plus a “,” , I have no idea where is this coming from
function palindrome(str) {
var newPalindrome = str.replace(/[^A-Za-z0-9]/g,’’);
var lowCaseString = newPalindrome.toLowerCase();
var reverseStr =lowCaseString.split(’’);
var finalString= reverseStr.reverse().join(’’);
if(finalString == reverseStr) return true;
else if (finalString != reverseStr)return false;
}