检查String是否是JavaScript中的Palindrome [英] Check if a String is a Palindrome in JavaScript

查看:65
本文介绍了检查String是否是JavaScript中的Palindrome的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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

这篇关于检查String是否是JavaScript中的Palindrome的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆