使用JavaScript计算字符串中的单词数 [英] Count number of words in string using JavaScript

查看:273
本文介绍了使用JavaScript计算字符串中的单词数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to count the number of words in a given string using the following code:

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

In that code I am getting data from a div tag and sending it to the cword() function for counting. Though the return value is different in IE and Firefox. Is there any change required in the regular expression? One thing that I show that both browser send same string there is a problem inside the cword() function.

推荐答案

您可以巧妙地使用replace()方法,但不要更换任何东西。

You can make a clever use of the replace() method although you are not replacing anything.

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标签,例如

the regex can be improved to exclude html tags for example

这篇关于使用JavaScript计算字符串中的单词数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆