I'm trying to check whether some sentence is a palindrome. Word breaks and punctuation don't count.
This code using cStr.split(" ")
DOES NOT accomplish the task.
Splitting on whitespace (" "), it seems like reverse() does nothing.
const palindromes = (str) => {
const regex = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g;
const cStr = str.toLowerCase().replace(regex, "").split(" ").join("");
const revStr = cStr.split(" ").slice().reverse().join("");
return cStr === revStr ? true : false;
};
UPDATED THOUGHTS: After I join the original string cStr
at the end, the characters are all collapsed. In the incorrect code I split on "whitespace" (split(" ")) which does not exist, so the code stops executing but doesn't throw an error?
The same code using [...cStr]
or cStr.split("")
DOES accomplish the task:
const revStr = cStr.split("").slice().reverse().join("");
// or
const revStr = [...cStr].slice().reverse().join("");
How is the "separator"; /""/ or /" "/ having this effect?
If separator is an empty string (""), str is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string.
Relevant question to array mutating: reverse-array-in-javascript-without-mutating-original-array
Relevant question to string manipulation: character-array-from-string
Split() doc: String.prototype.split()