任何给定DOM元素的Javascript字数 [英] Javascript word-count for any given DOM element

查看:52
本文介绍了任何给定DOM元素的Javascript字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法计算div中的单词。假设我们有这样的div:

I'm wondering if there's a way to count the words inside a div for example. Say we have a div like so:

<div id="content">
hello how are you?
</div>

然后让JS函数返回4的整数。

Then have the JS function return an integer of 4.

这可能吗?我已经使用表单元素完成了这项操作但似乎无法使用表单元素。

Is this possible? I have done this with form elements but can't seem to do it for non-form ones.

任何想法?

g

推荐答案

如果你知道DIV 只有将有文字它,您可以 KISS

var count = document.getElementById('content').innerHTML.split(' ').length;

如果div中可以包含HTML标签,那么您将不得不遍历其子项对于文本节点:

If the div can have HTML tags in it, you're going to have to traverse its children looking for text nodes:

function get_text(el) {
    ret = "";
    var length = el.childNodes.length;
    for(var i = 0; i < length; i++) {
        var node = el.childNodes[i];
        if(node.nodeType != 8) {
            ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
        }
    }
    return ret;
}
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;

这与jQuery库用于实现 text() 功能。 jQuery是一个非常棒的库,在这种情况下是没有必要的。但是,如果您发现自己正在进行大量DOM操作或AJAX,那么您可能需要查看它。

This is the same logic that the jQuery library uses to achieve the effect of its text() function. jQuery is a pretty awesome library that in this case is not necessary. However, if you find yourself doing a lot of DOM manipulation or AJAX then you might want to check it out.

编辑

正如Gumbo在评论中所指出的那样,我们分割上面的字符串的方式会将两个连续的空格统计为一个单词。如果你期望那种事情(即使你不这样做),最好通过分割正则表达式而不是简单的空格字符来避免它。记住这一点,而不是做上述分割,你应该这样做:

As noted by Gumbo in the comments, the way we are splitting the strings above would count two consecutive spaces as a word. If you expect that sort of thing (and even if you don't) it's probably best to avoid it by splitting on a regular expression instead of on a simple space character. Keeping that in mind, instead of doing the above split, you should do something like this:

var count = words.split(/\s+/).length;

唯一的区别在于我们传递给 split 功能。

The only difference being on what we're passing to the split function.

这篇关于任何给定DOM元素的Javascript字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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