目的 确定字符串是否是回文,忽略任何空格,特殊字符和大小写。
JAVASCRIPT
function palindrome(str) {
//remove punctuation, whitespace, capitalization, and special characters from original string -
var original = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"")
.replace(/\s/g," ").toLowerCase();
//take original sentence and reverse
var reverse = original.split('').reverse().join('');
//compare original vs reversed
if (original == reverse) {
return true;
} else {
return false;
}
}
palindrome("eye");
问题
答案 0 :(得分:2)
通过将\s
包含在字符类中(并添加缺少的常用特殊字符),可以将2个替换链式方法加入到1中:
var original = str.replace(/[\s"'.,-\/#!$%\^&*;:{}=\-_`~()\\\[\]@+|?><]/g,"").toLowerCase();
答案 1 :(得分:0)
现在您可以检查任何具有特殊字符(/ n,/ t _,#,%,2等)的字符串值
function palindrome(str)
{
var re = /[\W_]/g; // getting every special character
/*
[^A-Z] matches anything that is not enclosed between A and Z
[^a-z] matches anything that is not enclosed between a and z
[^0-9] matches anything that is not enclosed between 0 and 9
[^_] matches anything that does not enclose _
/[^A-Za-z0–9]/g or /[\W_]/g
*/
str = str.toLowerCase().replace(re, ''); // Remove every specal character
var len = str.length -1;
var mid = Number(len/2);
for ( var i = 0; i < mid; i++ )
{
if (str[i] !== str[len - i])
{
return " Not_Palindrome";
}
}
return "Palindrome";
}
var inputValue = "m_ad)am"; // input your Value
var outPutValue = palindrome(inputValue);
console.log(" the input value {" + inputValue + "} is :" + outPutValue);
//the input value {madam(} is :Palindrome