Pergunta

I'm working on a Jquery word counter that would show how many words a user has typed into a textbox as they go. That part is fine. My issue is that users are able to insert HTML into their posts to style it as they please (post templates/tables/etc). I managed to figure out how to remove html tags from being counted by the word counter, but my problem is how to handle tags.

For example, somebody could insert a post like this:

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

The word counter should only count 4 words (the four text's), but instead, it will also count .speech, color, .container, and width as well.

Here is the code that I've come up with so far: http://jsbin.com/aneray/85/edit

Any help or suggestions would be greatly appreciated, thanks!

Foi útil?

Solução

I used a div to set the text and remove anything that is not required for 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();
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top