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)
我更喜欢RegEx唯一的解决方案:
var str = "your long string with many words.";
var wordCount = str.match(/(\w+)/g).length;
alert(wordCount); //6Run 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)
括号围绕每个匹配创建一个组.因此,所有匹配组的长度应与单词计数匹配.
这是我找到的最佳解决方案:
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)。
尽管您没有替换任何内容,但您可以巧妙地使用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 标签
| 归档时间: |
|
| 查看次数: |
18814 次 |
| 最近记录: |