Estimate the read time of an article without any library in JavaScript.

Craft an estimated read time function from scratch!

In this article, we'll embark on a journey to craft a JavaScript function to help us estimate the read time of an article. You will dabble with a little bit of regex to help you strip your content clean for proper estimation. Keep in mind that since this is pure JavaScript, it works across the stack (front-end and back-end).

Let's get started.

Strip HTML Tags

If there are HTML tags present in your content, you will need to strip the content to make the estimation more accurate.

To do that, we have to do some regex:

const htmlTagRegExp = /<\/?[^>]+(>|$)/g
const textWithoutHtml = text.replace(htmlTagRegExp, '')
  • htmlTagRegExp: The regex function catches any HTML tag syntax.

  • textWithoutHtml: The .replace property replaces the HTML tag syntax caught by the regex with a blank space.

With that, we achieved the first phase of the estimation.

Match all words

const wordMatchRegExp = /[^\s]+/g
const words = textWithoutHtml.matchAll(wordMatchRegExp)
  • wordMatchRegExp: This regex function is used to match all non-whitespace characters. It's designed to match individual words in a text.

  • words: The matchAll method is used to find all matches of the regular expression in the given textWithoutHtml. It returns an iterator containing all the matches.

Let's Estimate!

To estimate the read time of the content, you will unpack words and get the length as the word count. Then you divide it by 200. Why? because 200 words per minute is the assumed average reading speed.

const wordCount = [...words].length
const readTime = Math.round(wordCount / 200)

With that, you have gotten the estimated read time of your content.

Conclusion

You can always set this up as a reusable function in your project and make use of it without installing any additional packages.

See you on the next one.