我正在研究一个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>
单词counter应该只计算4个单词(四个文本),但它也会计算.speech,color,.container和width。
以下是我迄今为止提出的代码:http://jsbin.com/aneray/85/edit
非常感谢任何帮助或建议,谢谢!
答案 0 :(得分:0)
我使用div来设置文本并删除word / char count不需要的任何内容。
DEMO: 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();
});