I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation.
The code snippet that utilizes cStr.split(" ")
DOES NOT achieve the desired outcome.
Although it splits on whitespaces (" "), calling reverse() seems ineffective in this case.
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;
};
FURTHER CONSIDERATIONS: Upon joining the original string cStr
at the end, the characters appear collapsed. In the flawed code example, splitting on "whitespace" (split(" ")) triggers the script to halt without throwing any errors?
The same logic applied with either [...cStr]
or cStr.split("")
DOES yield the intended result:
const revStr = cStr.split("").slice().reverse().join("");
// or
const revStr = [...cStr].slice().reverse().join("");
How does the choice of "separator" - /""/ or /" "/ impact this behavior?
If the separator is an empty string (""), the string is converted into an array of individual UTF-16 "characters", excluding empty strings at the ends.
Linked inquiry regarding array manipulation: reverse-array-in-javascript-without-mutating-original-array
Related query concerning string handling: character-array-from-string
Documentation for Split(): String.prototype.split()