JQuery 字数统计和从 HTML 中剥离标签

标签 jquery html

我正在尝试对接受 HTML 输入的文本区域进行字数统计。

我的第一步是从输入中删除标签。我从 another question 找到了这段代码:

$("<div></div>").html(html).text();

效果很好,但容易受到 html 中脚本标签的影响:

html = "<script>alert()";

我试图通过使用来缓解这个问题:

$("<p>").html(html).remove('script').text();

成功处理了上面的例子。不幸的是它不能处理:

html = "<script><script>alert();</script>";

因为它只删除外部脚本。

我正在尝试编写一个 while 循环来不断删除脚本,直到没有可删除的脚本为止,但我在逻辑上遇到了困难。

我想要这样的东西:

var $div = $("<div></div>").html(html);
while(*remove script causes a change*){
  $div = $div.remove('script');
}
text = $div.text();

这可能吗?这安全吗?

有没有办法也处理其他元素中的 onXXX="" 属性?

最佳答案

您可以使用此正则表达式:

var regex = /(<([^>]+)>)/ig
var body = "<p>test</p>"
var result = body.replace(regex, "");

alert(result);

在 StackOverflow 上找到了另一个答案: How to strip HTML tags from div content using Javascript/jQuery?

请在保存到数据库之前清理字符串。

关于JQuery 字数统计和从 HTML 中剥离标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36773918/

相关文章:

jquery - jqgrid 填充数据,但给 tr 一个 ID null

html - 使内容 div 填充剩余高度

html - 我可以使用 xpath 从内容字典中获取值吗?

javascript - 禁用所选选项后 select2 未更新

android - AJAX 调用不适用于 phonegap apk build

javascript - 我不知道这段代码是什么

javascript - 选择下拉方向

html - 如何验证文本区域中的模式匹配?

javascript - 处理选项卡按下事件以在可编辑的 html 表中添加动态自定义行

jquery - 查询 REST 服务的 JSONP 问题