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

时间:2011-07-01 05:26:55

标签: javascript internet-explorer-9 firefox3.5

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

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()函数内部存在问题。

5 个答案:

答案 0 :(得分:15)

您可以使用split并在String原型中添加wordcounter:

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

'this string has five words'.countWords(); //=> 5

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

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

'this string has seven ... words  - and counting'.countWords(); //=> 7

答案 1 :(得分:9)

我更喜欢仅限RegEx的解决方案:

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

正则表达式是

\w+    between one and unlimited word characters
/g     greedy - don't stop after the first match

括号围绕每场比赛创建一个组。因此,所有匹配组的长度应与字数匹配。

答案 2 :(得分: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);

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

答案 3 :(得分:0)

//Count words in a string or what appears as words :-)

        function countWordsString(string){

            var counter = 1;

            // Change multiple spaces for one space
            string=string.replace(/[\s]+/gim, ' ');

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

            return counter;
        }


        var numberWords = countWordsString(string);

答案 4 :(得分:0)

这是我发现的最佳解决方案:

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 '等字符串(如果将'correct'定义为0和4)。

相关问题