Can I make use of word-count.js in my own code?

After looking further through the source for word-count.js and then through various WordPress Trac entries I found satisfactory answers to my two questions:

Question 1: How can I use the word-count function?

To make use of the word count function you have to instantiate the wordcounter utility first:

var wc = new window.wp.utils.WordCounter();

and then you can access the count function, e.g:

var mywordcount = wc.count('Count these words');

or for character count you add in a type setting attribute using either ‘characters_excluding_spaces’ or ‘characters_including_spaces’:

var mycharcount = wc.count('Count these chars', 'characters_including_spaces');

I’d recommend reading through the source of word-count.js to see more about these attributes etc.

Question 2: Is it safe to use this core JS code in my own code?

After reading through some trac entries for word-count.js there seemed to be discussion about making this code reusable in other WordPress code, plugins etc (in particular in the recent Gutenberg editor development) so I’m reasonably happy that it’s safe to use this code in my own code. So, not a definitive ‘yes’ but I’m happy to make use of it in my own code.

(The only mystery remaining now is why the core word-count JS doesn’t treat numbers like “2017” as a word!!!)

Leave a Comment