Javascript word-count for any given DOM element

2020-02-17 10:08发布

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>

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.

Any ideas?

g

标签: javascript
8条回答
家丑人穷心不美
2楼-- · 2020-02-17 10:34

string_var.match(/[^\s]+/g).length - 1;

查看更多
祖国的老花朵
3楼-- · 2020-02-17 10:39

Paolo Bergantino's second solution is incorrect for empty strings or strings that begin or end with whitespaces. Here's the fix:

var count = !s ? 0 : (s.split(/^\s+$/).length === 2 ? 0 : 2 +
    s.split(/\s+/).length - s.split(/^\s+/).length - s.split(/\s+$/).length);

Explanation: If the string is empty, there are zero words; If the string has only whitespaces, there are zero words; Else, count the number of whitespace groups without the ones from the beginning and the end of the string.

查看更多
登录 后发表回答