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.
Top comments (1)
aking our read time estimation a step further, let's refine the process to consider not only words but also account for variations in reading speed. Instead of a fixed 200 words per minute assumption, allow users to set their own reading speed preferences. This personalization ensures a more accurate and user-centric estimate, enhancing the overall reading experience. Implement this adaptable approach in your estimation function for a touch of customization! šāļøš”
Here's a simple modification to your existing code that allows users to set their own reading speed:
Now, users can call the estimateReadTime function with the content of their article and optionally specify their preferred reading speed (words per minute). This customization allows for a more tailored estimate, catering to individual reading habits. Feel free to integrate this enhancement into your project for a personalized touch! šššØ