Use Liquid to count the number of words in a string

Reading time: 1 minute

Liquid doesn't come with a way to count how many words a given string contains. But there's a fairly easy way to determine that number with some clever use of Liquid filters.

Assume you want to show how many words a blog post has. You would take the content of the blog post (article) and start by removing remove all the HTML (because we don't want to count all that code). That leaves you with the raw text of the article.

Then you would split that by spaces. Words are separated by spaces, so if you split a text by single spaces, you get an array with one word per array item.

Once you have all the words in an array, all you have to do is use the size filter to determine how many elements – words – that array has.

Liquid's split filter conveniently treats multiple consecutive spaces as one. So if your article for some reason has multiple spaces somewhere, it won't skew the word count.

The final code looks like this:

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.