我需要创建一个接受字符串和布尔值的回文来验证几个条件。
现在,如果一个句子的镜像被镜像但是有不同的空格会导致错误,那么没有空格的相同字符会导致错误。
我的问题是需要忽略空格的下一个测试,如果字符确实是回文,则会在我的测试中返回 true 返回false。
这是我到目前为止所得到的(它们也是其他条件)
function palindrome(str) {
let reChar = str.toLowerCase().replace(/\w\s/g, '');
let checkPalindrome = reChar.split('').reverse().join('');
if (str === '') {
return false;
}
return (reChar === checkPalindrome);
}
感谢您的帮助
注意:我想我必须传递第二个参数,但我不知道如何。
答案 0 :(得分:1)
编辑:您似乎希望您的函数既支持忽略也不忽略空格。如果是这种情况,您可以传递一个标志来确定这一点。
// only use when ignoring whitespace
.replace(/\s/g, '');
此外,如果出现这种情况我们可以立即返回''
并且无需执行任何操作,那么您false
不能成为回文的特殊情况检查可以移至顶部。< / p>
示例:
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
)