How to count the number of words in wysiwyg editor javascript?

3.4k views Asked by At

I am using WYSIWYG editor, written there and saved it.

I just want to count the number of characters I have written.

Suppose I have written "My Count is 4", Then it should show me the count as 13

and after marking it bold or Italic the count should remain same as 13.

The code I am using to count is jQuery(selector).text().length;

But its returning me the data, along with html tags.

and if I have written "My Count is 4" in Bold in editor. The count is increasing, because its counting the html <b></b> tags also.

Please help me to find the solution.

1

There are 1 answers

5
StudioTime On BEST ANSWER

Try something like this:

// firstly we'll strip the html out
var myCode = jQuery('#getMe').html();
// strip out tags and line breaks
var cleanCode = myCode.replace(/<(?:.|\n)*?>/gm, '').replace(/(\r\n|\n|\r)/gm,"").replace('&nbsp;','');

// then count as normal
var numChars = cleanCode.trim().length;

Have a look at this fiddle