Hi I would like to do a Word Count in my RTE (Rich Text Editor) with javascript can also use with jquery. But it should not count the html tags and repeating white spaces.
嗨我想在我的RTE(富文本编辑器)中使用javascript也可以使用jquery。但它不应该计算html标签和重复空格。
Sample Text:
<h1>Hello World</h1> <p> This is Good!!!</p> answer <h2>thanks! </h2>
Hello World
这很好!!! 回答
谢谢!
The javascript should display 7 only.
javascript应该只显示7。
Is there any javascript code for this and that is also fast to calculate the Word Count?
是否有任何javascript代码,这也很快计算字数?
Thanks!
EDIT
What if the sample text is this: <p>11 22 33</p><p>44</p>5<br></div>
The javascript should display 5 only.
如果示例文本是这样的:
11 22 33
44
5
javascript应该只显示5。
1 个解决方案
#1
2
First you need to get text content of element. You can get text of element using text()
. Then you need to remove additional space of text. trim()
and replace(/[\s]+/g, " ")
remove additional space in text. Now you can convert text to word using split()
method.
首先,您需要获取元素的文本内容。您可以使用text()获取元素的文本。然后,您需要删除额外的文本空间。 trim()和replace(/ [\ s] + / g,“”)删除文本中的其他空格。现在,您可以使用split()方法将文本转换为单词。
var length = $(".text").text().trim().replace(/[\s]+/g, " ").split(" ").length;
console.log(length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
<h1>Hello World</h1>
<p> This is Good!!!</p>
answer
<h2>thanks! </h2>
</div>
#1
2
First you need to get text content of element. You can get text of element using text()
. Then you need to remove additional space of text. trim()
and replace(/[\s]+/g, " ")
remove additional space in text. Now you can convert text to word using split()
method.
首先,您需要获取元素的文本内容。您可以使用text()获取元素的文本。然后,您需要删除额外的文本空间。 trim()和replace(/ [\ s] + / g,“”)删除文本中的其他空格。现在,您可以使用split()方法将文本转换为单词。
var length = $(".text").text().trim().replace(/[\s]+/g, " ").split(" ").length;
console.log(length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
<h1>Hello World</h1>
<p> This is Good!!!</p>
answer
<h2>thanks! </h2>
</div>