replace()函数未按预期工作



replace函数并没有按预期工作。发现了这段代码。我知道替换功能是替换所有标点符号,这样就不会把它们算作字母。但当我记录一个包含标点符号的字符串时,它也会计算它们。试图找出的原因

const getLetterCount = (stringToTest) => {
const wordArray = stringToTest.split('');
let totalLetters = 0;
for (let word of wordArray) {
word.replace(/[.,/#!$%^&*;:{}=-_`~()]/g, "");
totalLetters += word.length;
}
console.log(totalLetters);
}
getLetterCount('boy/girl?')  // returns 9 ( counting punctuation as well)

String.protype.replacement((

replace()方法返回一个新字符串,其中模式的部分或全部匹配项被替换项替换。

您必须将新值重新分配给变量(word(。

const getLetterCount = (stringToTest) => {
const wordArray = stringToTest.split('');
let totalLetters = 0;
for (let word of wordArray) {
word = word.replace(/[.,/#!$%^&*;:{}=-_` ~()]/g, "");
totalLetters += word.length;
}
console.log(totalLetters);
}
getLetterCount('boy/girl?')  // returns 9 ( counting punctuation as well)

最新更新