JavaScript 的回文问题

Palindrome issue with JavaScript

我需要编写一个带有参数 str 的函数的代码,该参数评估单词是否为回文,它应该 return true,否则我应该return false.

注意:我需要删除所有非字母数字字符。

我写了下面的代码,但它给出了与预期结果相反的结果:

代码:

function palindrome(str) {
  var exc = /[^\w_]/gi;
  var repStr = str.toLowerCase().replace(exc, "");
  console.log("Replaced string id: " + repStr);
  len = repStr.length -1

  for (var i = 0; i <= len; i++) {
    if (str[i] !== repStr[len] - i) {
      return false;
    }
  }
  return true;
}

console.log(palindrome("eye"));
console.log(palindrome("_eye"));
console.log(palindrome("race car"));
console.log(palindrome("not a palindrome"));
console.log(palindrome("A man, a plan, a canal. Panama"));
console.log(palindrome("never odd or even"));
console.log(palindrome("nope"));
console.log(palindrome("almostomla"));
console.log(palindrome("My age is 0, 0 si ega ym"));
console.log(palindrome("1 eye for of 1 eye."));
console.log(palindrome("0_0 (: /-\ :) 0-0"));
console.log(palindrome("five|\_/|four"));

您的代码中有 2 个错误。 1) RegExp 没有替换下划线,因为 [^\w_] 读作 "everything that is not a word character OR an underscore"。尝试

/[\W_]/g

读作 "one of the following: any character that is not a word character, underscores"

/[^0-9a-z]/g

读作 "anything that is not: digits (from 0 to 9), english alphabet letters"。

2) 为了让它工作你需要写

if(repStr[i] !== repStr[len - i])

而不是

if(str[i] !== repStr[len] - i)

你可以简单地替换你的两行

for (var i = 0; i <= len; i++, len--) {
    if (str[i] !== repStr[len]) {

检查这个

function palindrome(str) {
  var exc = /[^\w_]/gi;
  var repStr = str.toLowerCase().replace(exc, "");
  console.log("Replaced string id: " + repStr);
  len = repStr.length -1

  for (var i = 0; i <= len; i++, len--) {
    if (str[i] !== repStr[len]) {
      return false;
    }
  }
  return true;
}

console.log(palindrome("eye"));
console.log(palindrome("_eye"));
console.log(palindrome("race car"));
console.log(palindrome("not a palindrome"));
console.log(palindrome("A man, a plan, a canal. Panama"));
console.log(palindrome("never odd or even"));
console.log(palindrome("nope"));
console.log(palindrome("almostomla"));
console.log(palindrome("My age is 0, 0 si ega ym"));
console.log(palindrome("1 eye for of 1 eye."));
console.log(palindrome("0_0 (: /-\ :) 0-0"));
console.log(palindrome("five|\_/|four"));

试试这个:

function palindrome(str) {
    const letters = str.replace(/[^a-z]/gi, ''); // replace any char that is not in the set [a-z] range
    const lowercase = letters.toLowerCase();
    const reversed = lowercase.split('').reverse().join('');
    return lowercase === reversed;
}