这就是我的例子。字符串是给定的。实现一个函数- detectPalindrom
,它可以检测回文字符串。
给出的参数不是字符串-返回‘传递的参数不是字符串’。
我写了一个解决方案,但效果不正确:
const detectPalindrome = (str) => {
const palindr = str.split('').reverse().join('')
if(str === '') {
return 'String is empty'
}
if (str === palindr) {
return 'This string is palindrome!'
}
if (str !== palindr) {
return 'This string is not a palindrome!'
}
}
发布于 2021-04-08 14:43:21
只需在创建palindr
字符串之前进行检查即可。
const detectPalindrome = (str) => {
if (typeof str !== "string") {
return 'Passed argument is not a string'
}
const palindr = str.split('').reverse().join('');
if (str === '') {
return 'String is empty';
}
if (str === palindr) {
return 'This string is palindrome!';
}
if (str !== palindr) {
return 'This string is not a palindrome!';
}
};
detectPalindrome("154");
发布于 2021-04-08 14:47:56
您需要通过只保留非空白字符来转义输入。你也可以把它细化,去掉一些特殊的字符。
const
reverse = str => str.split('').reverse().join(''),
escape = str => str.toLowerCase().replace(/[^\S]|[,;\.?!'"]/g, '');
const detectPalindrome = input => {
if (typeof input === 'string') {
if (input === '') return 'String is empty'
const
str = escape(input),
pal = reverse(str);
return str === pal
? 'This string is a palindrome!'
: 'This string is not a palindrome!';
} else {
return 'Passed argument is not a string';
}
}
console.log(detectPalindrome(0)); // 'Passed argument is not a string'
console.log(detectPalindrome('')); // 'String is empty'
console.log(detectPalindrome('Racecar')); // 'This string is a palindrome!'
console.log(detectPalindrome('Apple')); // 'This string is not a palindrome!'
console.log(detectPalindrome("Madam I'm Adam")); // TRUE
发布于 2021-04-08 14:48:39
const detectPalindrome = (str) => {
if (typeof str !== 'string')
return 'Passed argument is not a string'
const palindr = str.split('').reverse().join('')
if (str === '') {
return 'String is empty'
}
if (str === palindr) {
return 'This string is palindrome!'
}
if (str !== palindr) {
return 'This string is not a palindrome!'
}
}
console.log(detectPalindrome(123))
console.log(detectPalindrome(""))
console.log(detectPalindrome("abcd"))
console.log(detectPalindrome("lol"))
https://stackoverflow.com/questions/67006220
复制相似问题