如何避免问号使其不属于字符串的一部分?
例如:这里的返回值应该是 7 但它返回了 6,因为它没有考虑 'soup?'。如何避免问号?任何帮助表示赞赏。
function timedReading (maxLength, text) {
var sep = text.split(" ");
result = 0;
count = 0;
for(var i = 0; i < sep.length; i++) {
if(sep[i].length<=maxLength) {
result += sep[i];
count++;
}
}
return count;
}
timedReading(4,"The Fox asked the stork, 'How is the soup?'");
最佳答案
例如,您可以从特殊字符中过滤每个单词。
function timedReading(maxLength, text) {
var sep = text.split(" ");
result = 0;
count = 0;
for (var i = 0; i < sep.length; i++) {
if (sep[i].split('').filter(v => !/[^A-za-z0-9]/.test(v)).join('').length <= maxLength) {
result += sep[i];
count++;
}
}
console.log(count);
}
timedReading(4, "The Fox asked the stork, 'How is the soup?'");
关于javascript - 避免字符串中的问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42879600/