检查字符串是否是 JavaScript 中的回文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31090974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:15:52  来源:igfitidea点击:

Check if a String is a Palindrome in JavaScript

javascriptarrays

提问by Austin Hansen

The requirements for this task are that the code is returns a 'true' or 'false' for an input string. The string can be a simply word or a phrase. The other question does not address these needs. Please reopen and answer here. I am working on a function to check if a given string is a palindrome. My code seems to work for simple one-word palindromes but not for palindromes that feature capitalization or spaces.

此任务的要求是代码为输入字符串返回“真”或“假”。字符串可以是简单的单词或短语。另一个问题没有解决这些需求。请重新打开并在此处回答。我正在研究一个函数来检查给定的字符串是否是回文。我的代码似乎适用于简单的单字回文,但不适用于具有大写或空格的回文。

function palindrome(str) 
{
    var palin = str.split("").reverse().join("");

    if (palin === str){
        return true;
    } else {
        return false;
    }
}   

palindrome("eye");//Succeeds
palindrome("Race car");//Fails

回答by Walter Chapilliquen - wZVanG

First the string is converted to lowercase. Also, the characters that are not the alphabet are removed. So the string comparison becomes a array, then invert it, and convert it to string again.

首先将字符串转换为小写。此外,删除不是字母表的字符。所以字符串比较变成了一个数组,然后将它取反,再转换成字符串。

Step 1: str1.toLowerCase().replace(...) => "Race car" => "race car" => "racecar"
Step 2: str2.split("") => ["r","a","c","e","c","a","r"] => .reverse().join() => "racecar"
Result: str1 === str2

function palindrome(str) {
   str = str.toLowerCase().replace(/[^a-z]+/g,"");
   return str === str.split("").reverse().join("")
}

alert(palindrome("eye")); //true
alert(palindrome("Race car")); //true
alert(palindrome("Madam, I'm Adam")); //true

回答by KooiInc

Something like if (word === word.split('').reverse().join('')) {/*its a palindrome!*/}I'd say

就像if (word === word.split('').reverse().join('')) {/*its a palindrome!*/}我会说的

An isPalindromeString extention:

一个isPalindrome字符串extention:

String.prototype.isPalindrome = function () {
  var cleaned = this.toLowerCase().match(/[a-z]/gi).reverse();
  return cleaned.join('') === cleaned.reverse().join('');
}

var result = document.querySelector('#result');
result.textContent = "'eye'.isPalindrome() => " + 'eye'.isPalindrome() +
                     "\n'Something'.isPalindrome() => " + 'Something'.isPalindrome() +
                     "\n'Race Car'.isPalindrome() => " + 'Race Car'.isPalindrome() +
                     "\n'Are we not drawn onward, we few, drawn onward to new era?'.isPalindrome() => " + 
                        'Are we not drawn onward, we few, drawn onward to new era?'.isPalindrome() +
                     "\n'Never even or odd'.isPalindrome() => " + 'Never even or odd'.isPalindrome() +
                     "\n'Never odd or even'.isPalindrome() => " + 'Never odd or even'.isPalindrome();
;
<pre id="result"></pre>

回答by Adam Morsi

function palindrome(str) {
    let letters = str.split('').filter(function (str) {
        return /\S/.test(str);
    });
    let reversedLetters = str.split('').reverse().filter(function (str) {
        return /\S/.test(str);
    });

    for (let i = 0; i < letters.length; i++) {
        if (letters[i].toLowerCase() !== reversedLetters[i].toLowerCase()) {
            return false;
        }
    }
    return true;
}
console.log(palindrome("eye")); //true
console.log(palindrome('Race car')); //true

回答by stefan

const palindromes = arrayOfWords.filter((item) => {
    return item === item.split('').reverse().join('');
})

This is an example :-)

这是一个例子:-)

回答by Vahid Akhtar

Palindrome using ES6

使用 ES6 的回文

const checkPalindrome=(str)=> {
  return str.toLowerCase().trim() === str.toLowerCase().trim().split('').reverse().join('');
}
console.log(checkPalindrome("Level "))

回答by Arslan Mujeeb

function palindrome(str) {

  var st='';    
  st=str.replace(/[^a-z0-9]/ig,"").toLowerCase();    
  var arr=[];    
  arr=st.split('');    
  arr=arr.reverse();    
  var strr='';    
  strr=arr.join('');
  if(strr==st) {
     return true;
 }
 return false;
}    
palindrome("A man, a plan, a canal. Panama");//calling the function

回答by Yakir Fitousi

//1. change the string to an array //2. use the reverse method //3. return the array as a string //4. return input= new reversed string

//1. 将字符串更改为数组 //2。使用反向方法//3。将数组作为字符串返回 //4。返回输入=新的反转字符串

var lowerCasedString = inputString.toLowerCase(); var reversedString = lowerCasedString.split("").reverse().join(""); return reversedString === lowerCasedString;
}
hope this would be helpful:

var lowerCasedString = inputString.toLowerCase(); var reversedString = lowerCasedString.split("").reverse().join(""); return reversedString === lowerCasedString;
}
希望这会有所帮助: