javascript - 避免字符串中的问号

标签 javascript string for-loop split

如何避免问号使其不属于字符串的一部分?

例如:这里的返回值应该是 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/

相关文章:

javascript - javascript帮助中的概率?

javascript - 在 div 向下滚动时加载结果

javascript - angularjs - $http 读取 json 并等待回调

string - 测试字符串是否包含文字星号

php - 内部连接与 foreach 循环性能

javascript - 如何删除基本jquery slider bjqs.js插件中标记中的文本内容

ios - 抓取字符串中的特定行 - Swift

python - 将当前元素与列表中的下一个元素合并

c - 在 C 中使用二维数组

python - Pandas:迭代连接存储在数据框字典中的列