使用 JavaScript 计算字符串中的单词数

新手上路,请多包涵

我正在尝试使用以下代码计算给定字符串中的单词数:

 var t = document.getElementById('MSO_ContentTable').textContent;

if (t == undefined) {
  var total = document.getElementById('MSO_ContentTable').innerText;
} else {
  var total = document.getElementById('MSO_ContentTable').textContent;
}
countTotal = cword(total);

function cword(w) {
  var count = 0;
  var words = w.split(" ");
  for (i = 0; i < words.length; i++) {
    // inner loop -- do the count
    if (words[i] != "") {
      count += 1;
    }
  }

  return (count);
}

在该代码中,我从 div 标签获取数据并将其发送到 cword() 函数进行计数。虽然返回值在 IE 和 Firefox 中是不同的。正则表达式是否需要任何更改?我表明两个浏览器发送相同字符串的一件事是 cword() 函数内部存在问题。

原文由 V_B 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 679
2 个回答

尽管您没有替换任何东西,但您可以巧妙地使用 replace() 方法。

 var str = "the very long text you have...";

var counter = 0;

// lets loop through the string and count the words
str.replace(/(\b+)/g,function (a) {
   // for each word found increase the counter value by 1
   counter++;
})

alert(counter);

例如,可以改进正则表达式以排除 html 标记

原文由 Ibu 发布,翻译遵循 CC BY-SA 3.0 许可协议

[ edit 2022 , based on comment] 如今,人们不会以这种方式扩展原生原型。一种在没有命名冲突危险的情况下扩展本机原型的方法是使用 es20xx symbol这是使用它的 wordcounter 的示例

旧答案:您可以使用 split 并将 wordcounter 添加到 String 原型:

 if (!String.prototype.countWords) {
  String.prototype.countWords = function() {
    return this.length && this.split(/\s+\b/).length || 0;
  };
}

console.log(`'this string has five words'.countWords() => ${
  'this string has five words'.countWords()}`);
console.log(`'this string has five words ... and counting'.countWords() => ${
  'this string has five words ... and counting'.countWords()}`);
console.log(`''.countWords() => ${''.countWords()}`);

原文由 KooiInc 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题