例如,我想知道是否有一种方法可以计算div中的字数。假设我们有这样一个div:
<div id="content">
hello how are you?
</div>
然后让JS函数返回一个整数4。
这个是可能的吗?我已经用表单元素做到了这一点,但似乎不能对非表单元素做到这一点。
有什么想法吗?
G
发布于 2012-07-18 01:46:33
string_var.match(/[^\s]+/g).length
看起来这是一种比
string_var.split(/\s+/).length
至少它不会将"word“算作2个单词-- 'word‘而不是'word','’。而且它并不需要任何有趣的附加逻辑。
发布于 2013-07-22 20:43:20
或者只是使用Countable.js来完成困难的工作;)
发布于 2009-04-20 00:32:12
document.deepText= function(hoo){
var A= [];
if(hoo){
hoo= hoo.firstChild;
while(hoo!= null){
if(hoo.nodeType== 3){
A[A.length]= hoo.data;
}
else A= A.concat(arguments.callee(hoo));
hoo= hoo.nextSibling;
}
}
return A;
}
我对单词的定义相当严格-
function countwords(hoo){
var text= document.deepText(hoo).join(' ');
return text.match(/[A-Za-z\'\-]+/g).length;
}
alert(countwords(document.body))
https://stackoverflow.com/questions/765419
复制相似问题