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

I want to implement word and character counts on custom fields (such as inputs or textareas) but rather than writing my own code I would like to make use of the native word-count.js code that is part of WordPress core codebase:

https://github.com/WordPress/wordpress-develop/blob/master/src/wp-admin/js/word-count.js

However, I’ve got a couple of questions:

  1. I’m not sure how to actually make use of that function in my
    own code. How I would actually make use of the code on a field of my
    own?
  2. Presuming there is some kind of answer to my first question, is it safe to make use of this code or should this be
    treated more like a private API not intended for public use, e.g.
    something that might change in a future release?

I know there are various word count plugins out there that I could use (I actually have my own word and character count JS code that I could make use of) it just seems like it would be much better to make use of the core WordPress word count code as it will definitely cover more edge cases such as encoding / localisation issues.

1 Answer
1

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