Reputation: 13
I need to create a palindrome that accepts a string and boolean to validate several conditions.
Now if a sentence has the letters mirrored but has different spaces will result false, same characters without whitespace present will result false.
My problem is the next test which needs to ignore the whitespace and if the characters are indeed palindromic will return true in my test return false.
This is what I got so far (they are other conditions to be passed as well)
function palindrome(str) {
let reChar = str.toLowerCase().replace(/\w\s/g, '');
let checkPalindrome = reChar.split('').reverse().join('');
if (str === '') {
return false;
}
return (reChar === checkPalindrome);
}
Thanks for any help
Note: I think I have to pass a 2nd parameter but I don't have an idea how.
Upvotes: 1
Views: 84
Reputation: 35491
EDIT: it seems that you want your function to support both ignoring and not ignoring whitespace. If that's the case you can pass a flag to determine this.
// only use when ignoring whitespace
.replace(/\s/g, '');
Furthermore, your special case check that makes ''
not be a palindrome can be moved to the top since we can return false
immediately if this is the case and there's no need to do anything:
Example:
function palindrome(str, ignoreWS) {
if (str === '') {
return false;
}
let reChar = ignoreWS
? str.toLowerCase().replace(/\s/g, '')
: str.toLowerCase();
let checkPalindrome = reChar.split('').reverse().join('');
return (reChar === checkPalindrome);
}
console.log(
palindrome('a b c cb a', true) // true
)
console.log(
palindrome('a b c cb a') // false
)
console.log(
palindrome('abccba') // true
)
console.log(
palindrome('') // false
)
Upvotes: 1