I’m now at the “check for palindromes”. below is my solution and it works. but I wonder if the code can be improved so it can work better? Also I’m interested to know how you solve this problem?
function palindrome(str) {
var newStr = str.replace(/[^A-Za-z0-9]/gi, "").toLowerCase();
var result = newStr.split("").reverse().join("");
if(result === newStr){
return true;
} else{
return false;
}
}
palindrome("eye");
I searched and found that string.replace(/[^9-Za-z0-9]/g, “”) can be used to remove all non-alphanumeric chars. however, I don’t understand why [^9-Za-z0-9] removes non-alphanumeric chars. can someone please help me to understand?
function palindrome(str) {
//use a regular expression to find unusables & make lowercase
var newStr = str.replace(/\W+/g, "").replace(/_/g, "").toLowerCase();
//reverse the string
var newArray = newStr.split('');
newArray.reverse();
var reversed = newArray.join('');
//test if the palindrome is there or not
return newStr == reversed;
}
palindrome('_eye');
A quick run down of the comparison operator I used;
To test if something is true / false, you can simply return the comparison operator shown below
==
or
===
These both operate identically but the triple comparison operator will ignore any type conversion that may need to be done. For example, if you where to compare
0 == '0'
this would return true. The double comparison will convert the number to a string in order to compare the two. And since the string ‘0’ and ‘0’ are the same, it returns true. The triple comparison will return false because the two are not the same type. A string is not a number.
Hi thanks for pointing out the flaws.
regarding the regex, /[^a-z0-9]g/ can be used to remove all non-alphanumeric chars? how is it different to (/[^A-Za-z0-9]/gi that I used?
thanks!
Hi, I just tried replacing str.replace(/[^A-Za-z0-9]/gi, “”).toLowerCase(); with str.toLowerCase().replace(/[^a-z0-9]g/, “”); however, it didn’t pass the tests. anything wrong?