<style> 使用 Jquery 删除文本区域内标签之间的所有内容



我正在开发一个Jquery单词计数器,它可以显示用户在文本框中键入的单词数量。那部分很好。我的问题是,用户可以将HTML插入到他们的帖子中,以按照自己的意愿进行样式设置(帖子模板/表格等)。我设法弄清楚了如何从单词计数器的计数中删除html标签,但我的问题是如何处理标签。

例如,有人可以插入这样的帖子:

<style>
.speech {color:#000;font-weight:bold;}
.container {width:80%;}
</style>
<div class="container">
text text text <span class="speech">text</span>
</div>

单词计数器应该只计算4个单词(四个文本),但它也会计算.speech、color、.contator和width。

以下是我迄今为止提出的代码:http://jsbin.com/aneray/85/edit

如有任何帮助或建议,我们将不胜感激,谢谢!

我使用div来设置文本,并删除单词/字符计数不需要的任何内容。

演示:http://jsbin.com/aneray/88/edit

function count(){
  var $t = $('<div />').html($('textarea').val());
  $t.find('style').remove(); //remove style content
  txtVal = $t.text(); //fetch the text, ignore the tags
  var words = txtVal.trim().replace(/s+/gi, ' ').split(' ').length;
  var chars = $.trim(txtVal).length; //trim any additional spaces, remove $.trim to include white spaces and additional space from tag line breaks
  if(chars===0){words=0;}
  $('#counter').html('<br>'+words+' words and '+ chars +' characters');
}
count();
$('textarea').on('keyup propertychange paste', function(){ 
    count();
});

最新更新