Calculate average reading time in JavaScript
One of the most used functions these days is the calculation of reading time. I even use it on this blog.
Why? It's simply a quick way to tell the user how much time they can spend on the article, maybe it's very fast (like this one) or maybe it takes a little longer.
Here I will show you a quick trick to get it:
The code
First of all, I will show you the code I use for this functionality, and then I will explain it:
1/**2 * Calculate the average reading time of a text3 */4function readingTime(text: string): number {5 const WORDS_PER_MINUTE: number = 225;6 const words: number = text.trim().split(/\s+/).length;78 return Math.ceil(words / WORDS_PER_MINUTE);9}10
The explanation
As you can see, it's a pretty simple piece of code, basically what we do is:
- We define a constant
WORDS_PER_MINUTE
that will give us a base for our calculation, normally ranges between 150 and 300 (words per minute) depending on the level and age of the person, so we will use 2251 text.trim()
removes the spaces at the beginning and end of the text, so that always starts and ends with a letter, number, or symbol.split(/\s+/)
“cuts” all the text at each space and stores it in anarray
.length
returns the total number of elements in the array, our number of wordsMath
is the JavaScript library that provides functions for calculations.ceil
is a rounding function, it means that it will round up to the nearest whole number (for example 52.2 will become 53)2- Finally, we divide our total words by our constant of
words per minute (
words / WORDS_PER_MINUTE
), and we will have as a result the number of minutes it would take an average person to read the text
That's it! If we want to go a step further we can convert it to hours or save it in seconds to have better control, but basically this is all we need.
Avobe and Beyond
As you can see the function takes a text to calculate the time, if we want to make it a little more automatic we can make it take the text from an HTML element, or from a file, or from any other source we can think of.
For example:
1const text = document.querySelector('.article').innerText; // It is important to use \`innerText\`;23readingTime(text);4
Why do we use innerText
instead of innerHTML
?
Because innerText
returns the text without tags,
while innerHTML
returns the text with tags.
If we use innerHTML
we would be counting the tags as words,
which is not what we want.
I hope it helps you as much as it has helped me, greetings!