我試圖讓使用javascript迴文程序,將顯示一個字符串是否是迴文或不TRUE或FALSE即使字符串具有標點符號和空格(如 - 女士,我是亞當)。但每次我把一個字符串,我只得到真無論字符串是什麼。這裏是我的代碼,迴文計劃,避免在Javascript
function isPalindrome (str) {
var nopunctuation = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var nospaces = nopunctuation.replace(/\s/g,"");
var finalstring = nospaces;
var len = finalstring.length;
for (var i = 0; i < Math.floor(finalstring/2); i++) {
if (finalstring[i] !== finalstring[len - 1 - i]) {
return false;
}
}
return true;
}
console.log(isPalindrome("madam i'm adam"));
我的代碼有什麼問題嗎?需要注意的是,我不允許使用任何內置或庫函數。你的幫助將非常可觀。 TNX。
扭轉它,使用'finalstring.split( '')( ')'然後比較反向()加入。'。例如'String.prototype.isPalindrome = function(){var a = this.replace(/ [^ a-zA-Z] | \ s/g,'')。toLowerCase(); return a == a.split(' ').reverse()。join('');}' – 2014-12-02 13:11:45
哦,很抱歉之前提過但我不能使用任何內置或庫函數來解決這個問題。如果你知道我在說什麼,我必須以一種純粹的方式去做。 – 2014-12-02 13:13:20
@akz,不行不行。 – 2014-12-02 13:13:41