【问题标题】:.text() concatenates strings without spaces when removing html tags.text() 删除 html 标记时连接不带空格的字符串
【发布时间】:2019-02-15 19:51:28
【问题描述】:

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

因为它是一个富文本编辑器,它(可能)包含 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

如您所见,“标题”“和”这两个词被连接成“标题和”,这将使我的字数变为 10 而不是 11。

任何关于如何正确实现这一点的想法将不胜感激:)

【问题讨论】:

  • 看起来程序忽略了空格以外的空格。可能会提供线索

标签: javascript jquery html string concatenation


【解决方案1】:

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

【讨论】:

  • 效果很好 - 感谢 Denys(因为没有在 jquery 框之外思考而打了自己一巴掌:p)
  • 别打自己太重:由于历史原因,innerText 并不为人所知(来自微软并被视为“非标准”)
  • 你也可以使用.replace(/\s+/g, " ")从字符串中删除额外的空间。
  • 哈哈,我会轻轻一巴掌……虽然不太出名,但我假设它得到了很好的支持?
  • @ronnieburns 是的,所有浏览器都支持它
【解决方案2】:

我玩了一下,想出了以下几点:

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

只要修剪和分割就可以了。

【讨论】:

  • 提示:在编写/编辑关于 html/js/css 的问题时,您应该看看工具栏中的 sn-p 按钮
  • 感谢您的提示,实际上正在尝试实现这一目标
猜你喜欢
  • 2012-05-10
  • 2010-09-19
  • 2017-09-06
  • 2011-12-14
相关资源
最近更新 更多