Javascript Check For Palindrome (spaces & Punctuation Included)
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
Solution 1:
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, "")
Solution 2:
Solution 3:
You can try with a simpler regex which simply replaces any character that is not in the alphabet?
functionpalindrome(str) {
if(str.replace(/[^a-zA-Z]/g, "").toLowerCase() === str.replace(/[^a-zA-Z]/g, "").toLowerCase().split("").reverse().join("")){
returntrue;
} else {
returnfalse;
}
}
Solution 4:
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('');
}
Post a Comment for "Javascript Check For Palindrome (spaces & Punctuation Included)"