.text()在删除html标签时将字符串连接在一起且没有空格

时间:2018-09-11 10:19:18

标签: javascript jquery html string concatenation

我的网站上有一个RTF编辑器,我正在尝试为其创建可靠的文字计数器。

因为它是一个富文本编辑器,所以它(可能)包含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”和“ and”结合在一起成为“ headingand”,这使我的单词数为10而不是11。

任何有关如何正确实现此目标的想法将不胜感激:)

2 个答案:

答案 0 :(得分:5)

您可以使用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>

答案 1 :(得分:0)

我在玩弄它,并提出了以下建议:

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

只需修剪并拆分,就可以了。

相关问题