Reputation: 6158
Trying to check for palindromes. I've checked other answers but none included punctuation & spaces.
"never odd or even" and "A man, a plan, a canal. Panama" Should return true but they don't.
function palindrome(str) {
if(str.replace(/[^\w\s]|_/g, "").toLowerCase() === str.replace(/[^\w\s]|_/g, "").toLowerCase().split("").reverse().join("")){
return true;
} else {
return false;
}
}
palindrome("eye");
Upvotes: 1
Views: 2346
Reputation: 1
To work with unevenly spaced numbers in a string, punctuation and uppercase letters, you can use
let regex = /[^a-zA-Z0-9]/g;
return (
str.replace(regex, "").toLowerCase() ===
str.replace(regex, "").toLowerCase().split("").reverse().join("")
);
Upvotes: 0
Reputation: 1
This is similar to the above but reformatted:
function palindrome(str) {
let regex = /[^a-zA-Z]/g;
return str.replace(regex, '').toLowerCase() === str.replace(regex, '').toLowerCase().split('').reverse().join('');
}
Upvotes: 0
Reputation: 4383
I think you have an error in your RegEx. If you want to remove the spaces, you don't need that \s
. Try changing:
str.replace(/[^\w\s]|_/g, "")
With
str.replace(/[^\w]|_/g, "")
Upvotes: 3
Reputation: 2167
You can try with a simpler regex which simply replaces any character that is not in the alphabet?
function palindrome(str) {
if(str.replace(/[^a-zA-Z]/g, "").toLowerCase() === str.replace(/[^a-zA-Z]/g, "").toLowerCase().split("").reverse().join("")){
return true;
} else {
return false;
}
}
Upvotes: 0
Reputation: 6467
Use instead:
str.replace(/\W/g, "")
Which will replace any non-word char by empty string.
Upvotes: 2