来自HTML的JQuery字数和剥离标签

时间:2016-04-21 15:19:37

标签: jquery html

我正在尝试对接受HTML输入的textarea进行字数统计。

我的第一步是从输入中删除标签。我从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=""属性?

2 个答案:

答案 0 :(得分:3)

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

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?

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

答案 1 :(得分:0)

我决定使用php函数phpjsstrip_tags版本,它似乎运行良好,并且很好地处理脚本标记。

到目前为止我的简单字数统计功能是:

$('#input').on('input',function(){
    var text = $(this).val();
    text = strip_tags(text).replace(/\s+/g, ' ').trim();
    var wordCount = 0;
    if(text != ''){
      var words = text.split(' ');
      wordCount = words.length;
    }

    $('#word-count').html(wordCount);
});
相关问题