我的网站上有一个富文本编辑器,我正在尝试为它创建一个可靠的文字计数器。
因为它是一个富文本编辑器,它(可能)包含html。
这个html可能是,例如:
<div class="textEditor">
<h1><strong>this is a sample heading</strong></h1>
<p><br></p>
<p>and this is a sample paragraph</p>
</div>
为了获得可靠的单词计数,我试图首先使用以下方法将html转换为文本:
var value = $('.textEditor').text()
我面临的问题是返回的字符串似乎连接在哪里删除html标签和我剩下的是:
this is a sample headingand this is a sample paragraph
正如你所看到的,'heading'和'这两个词被加入成为'headingand',它会给我一个10而不是11的字数。
任何关于如何正确实现这一点的想法将非常感谢:)
你可以使用innerText
:
var value = document.querySelector('.textEditor').innerText
要么
var value = $('.textEditor')[0].innerText
console.log(document.body.innerText)
<div class="textEditor">
<h1><strong>this is a sample heading</strong></h1>
<p><br></p>
<p>and this is a sample paragraph</p>
</div>
我有点玩弄它并提出以下内容:
let value = $('.textEditor').text();
function read(){
alert(value.trim().split(/\s+/).length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="textEditor">
<h1><strong>this is a sample heading</strong></h1>
<p><br></p>
<p>and this is a sample paragraph</p>
</div>
<button onclick="read()">Read</button>
https://codepen.io/anon/pen/YOazqG?editors=1010
修剪它并分开,你应该没事。