用于计算单词的javascript正则表达式

时间:2012-05-18 13:12:29

标签: javascript regex

我得到了这个代码来计算html编辑器中的单词数。

(providing htmlData has already been set)
var rawWords = htmlData.replace(/<(?:.|\s)*?>/g, '')
                       .replace(/(\r\n|\n|\r)/gm,' ');
var filteredWords = rawWords.replace(/\[([^\]]+)\]/g,'')
                            .replace(/\s+/g, " ")
                            .replace(/^\s+|\s+$/g, "");

据我所知,第一行删除了html,然后删除了任何返回。

下一行删除括号中的任何内容(这是添加注释而不影响字数),然后删除多余的空格

但如果我输入:

Apple


Charlie

Tom

它给了我一个6的字数,而不是3.任何想法为什么?我不擅长正则表达式!!!!

非常感谢

3 个答案:

答案 0 :(得分:1)

这些正则表达式是丑陋和多余的。我的建议是通过执行以下操作来获取清理的HTML:

var a=document.createElement('div')
a.innerHTML=htmlData;
textData=a.innerText

然后用一个简单的正则表达式遍历这个并增加一个计数器:

var patt=new RegExp(/(^|\W)(\w+)($|\W)/g);
var counter=0;
var result=patt.exec(textData);
while(result!=null) {
  counter++;
  result=patt.exec(textData);
}

这是非常粗糙的(并且做出了许多可能对你不起作用的假设)但是,你/你会得到“单词”的数量[你必须处理的定义],并且在获得您所说的内容之前,您不必更换和删除大量文本。

HTH

答案 1 :(得分:1)

试试这个,很简单,只需拆分空格/数字,然后对数组进行计数。

window.onload = function() {

    // get string as text
    var text = document.body.innerText;

    // replace all non letters (so we don't count 1 as a word)
    text     = text.replace(/[^a-zA-Z\s]/g, '');

    // split on whitespace
    var words = text.split(/[\s]+/);

    // output -- 52
    console.log('numwords', words, words.length); // numwords 52
}

以下完整示例:

<html>
<head>
<script type="text/javascript">// script</script>
</head>
<body>

a b c d e f g
1 1 1 1 1 1 1




the quick brown fox jumped over the lazy dog.
the quick brown fox jumped over the lazy dog.
the quick brown fox jumped over the lazy dog.<br><br><br><br><br>
the quick brown fox jumped over the lazy dog.
the quick brown fox jumped over the lazy dog.

</body>
</html>

答案 2 :(得分:0)

用“”替换空格不起作用。 尝试:

 .replace(/[ ]{2,}/gi," ");  /*{2,}=repeated*/
 .replace(/(^\s*)|(\s*$)/gi,"");

而不是:

.replace(/\s+/g, " ")
.replace(/^\s+|\s+$/g, "");

它应该可以正常工作。