避免在字符串中的问号

时间:2017-03-18 20:40:07

标签: javascript string for-loop split

如何避免使用问号,使其不会成为字符串的一部分?

例如:这里的返回值应为7,但它返回6,因为它没有考虑'汤?'。如何避免问号呢?任何帮助表示赞赏。

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?'");

1 个答案:

答案 0 :(得分:2)

你可以,例如从特殊字符中过滤每个单词。

&#13;
&#13;
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?'");
&#13;
&#13;
&#13;