JavaScript - 查找字符串是否为回文 - 检查标点符号

fud*_*din 0 javascript

我正在尝试解决练习,但代码显示错误.以下是练习的条件:

如果给定的字符串是回文,则返回true.否则,返回false.

  1. 您需要删除标点符号并将所有小写字母翻转以检查回文.
  2. 我们将传递不同格式的字符串,例如"racecar","RaceCar"和"race CAR"等.

我的尝试:

function palindrome(str) {
    str = str.toLowerCase();
    str = str.replace(",", "");
    str = str.replace(".", "");
    str = str.replace(":", "");
    str = str.replace(";", "");
    str = str.replace("-", "");
    str = str.replace(",", "");
    str = str.replace(" ", "");
    for (var i = 0; i <= (str.length / 2); i++) {
        if (str[i] != str.length - i) return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*rus 5

你很亲密.
更换:

if (str[i] != str.length-i)
Run Code Online (Sandbox Code Playgroud)

附:

if (str[i] != str[str.length - (i + 1)])
Run Code Online (Sandbox Code Playgroud)

字符串的最后一个字符是at str.length - (i + 1),你忘了得到实际的字符.相反,您将它与该角色的索引进行比较.

现在,你可以缩短功能很多:

function checkPalindrome(str) {
    // remove punctuation, to lower case.
    str = str.replace(/[.,?:;\/() _-]/g, '').toLowerCase();
    // Compare the string with it's reversed version.
    return str == str.split('').reverse().join('');
}
Run Code Online (Sandbox Code Playgroud)