這些是 The Odin Project 中的回文問題,我做的一切都很完美,但是在最后一個挑戰中,當程式需要回傳 false 時,它??不會發生。我試圖用該完整的字串更改 str ,但該函式繼續回傳 true。
回文是一個前后拼寫相同的字串,通常不考慮標點符號或分詞:
一些回文:
- 一輛車,一個人,一個馬拉卡。
- 老鼠生活在沒有邪惡的星星上。
- 蓋上一朵水仙花。
- 動物掠奪糞便層的葉狀細節。
- 一罐金槍魚的堅果。
const palindromes = function (str) {
str = str.replace('/[áà?a?]/ui', 'a');
str = str.replace('/[éèê?]/ui', 'e');
str = str.replace('/[íì??]/ui', 'i');
str = str.replace('/[óò???]/ui', 'o');
str = str.replace('/[úù?ü]/ui', 'u');
str = str.replace('/[?]/ui', 'c');
str = str.replace('/[^a-z0-9]/i', '');
str = str.replace('/_ /', '');
str = str.replace("!", "");
let reverseString = str.split().reverse().join();
let polishedString = reverseString;
if (polishedString === str) {
return true;
}
else {
return false;
}
};
palindromes("ZZZZ car, a man, a maracaz.");
// Do not edit below this line
module.exports = palindromes;
我的 If/Else 條件有什么問題?
uj5u.com熱心網友回復:
您應該使用.split('')字母拆分。而.join('')不是.join().
const palindromes = function (str) {
str = str.replace('/[áà?a?]/ui', 'a');
str = str.replace('/[éèê?]/ui', 'e');
str = str.replace('/[íì??]/ui', 'i');
str = str.replace('/[óò???]/ui', 'o');
str = str.replace('/[úù?ü]/ui', 'u');
str = str.replace('/[?]/ui', 'c');
str = str.replace('/[^a-z0-9]/i', '');
str = str.replace('/_ /', '');
str = str.replace("!", "");
let reverseString = str.split('').reverse().join('');
return reverseString === str;
};
console.log(palindromes("ZZZZ")); // true
console.log(palindromes("ZZZZ car, a man, a maracaz.")); // false
uj5u.com熱心網友回復:
split 和 join 方法中缺少空字串引數。
const palindromes = function (str) {
let polishedStr = str;
polishedStr = polishedStr.replace('/[áà?a?]/ui', 'a');
polishedStr = polishedStr.replace('/[éèê?]/ui', 'e');
polishedStr = polishedStr.replace('/[íì??]/ui', 'i');
polishedStr = polishedStr.replace('/[óò???]/ui', 'o');
polishedStr = polishedStr.replace('/[úù?ü]/ui', 'u');
polishedStr = polishedStr.replace('/[?]/ui', 'c');
polishedStr = polishedStr.replace('/[^a-z0-9]/i', '');
polishedStr = polishedStr.replace('/_ /', '');
polishedStr = polishedStr.replace("!", "");
let reverseString = polishedStr.split("").reverse().join(""); //the empty string were missing here in split and join method.
console.log(reverseString, polishedStr);
if (reverseString === polishedStr) {
return true;
}
return false;
};
console.log(palindromes("ZZZZ car, a man, a maracaz."));
// Do not edit below this line
//module.exports = palindromes;
uj5u.com熱心網友回復:
您可以嘗試使用這樣的正則運算式:
const palindromes = function (str) {
const compareStr = str.toLowerCase().replace(/[^\w]/g, '');
const reverseStr = compareStr.split('').reverse().join('');
return (compareStr === reverseStr)
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488780.html
標籤:javascript html 正则表达式 细绳 条件语句
