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

V_B*_*V_B 9 javascript firefox3.5 internet-explorer-9

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

Koo*_*Inc 16

您可以使用splitwordcounter并将其添加到String原型中:

String.prototype.countWords = function(){
  return this.split(/\s+/).length;
}

'this string has five words'.countWords(); //=> 5
Run Code Online (Sandbox Code Playgroud)

如果你想在一个句子中排除......或 - 之类的东西:

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

'this string has seven ... words  - and counting'.countWords(); //=> 7
Run Code Online (Sandbox Code Playgroud)


Dan*_*elH 9

我更喜欢RegEx唯一的解决方案:

var str = "your long string with many words.";
var wordCount = str.match(/(\w+)/g).length;
alert(wordCount); //6
Run Code Online (Sandbox Code Playgroud)

正则表达式是

\w+    between one and unlimited word characters
/g     greedy - don't stop after the first match
Run Code Online (Sandbox Code Playgroud)

括号围绕每个匹配创建一个组.因此,所有匹配组的长度应与单词计数匹配.

  • 这可能是处理长文本时最有效的方法。 (2认同)
  • 很好的解决方案,但如果输入字符串的长度为0或者都是空白,它会产生错误. (2认同)

aar*_*ron 5

这是我找到的最佳解决方案:

function wordCount(str) { var m = str.match(/[^\s]+/g) return m ? m.length : 0; }

这会反转空白选择,这比\w+因为它只匹配拉丁字母和 _更好(参见http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.2.6

如果您对空格匹配不小心,您将计算空字符串、带有前导和尾随空格的字符串以及所有空格字符串作为匹配项,而此解决方案正确处理类似' ', 的字符串' a\t\t!\r\n#$%() d '(如果您将“正确”定义为 0 和 4)。


Ibu*_*Ibu 3

尽管您没有替换任何内容,但您可以巧妙地使用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);
Run Code Online (Sandbox Code Playgroud)

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