When starting this blog, I was inspired by other websites and realized that they all display the time it takes to read a post.
But how is it done? Here’s the snippet. 😉
function readingTime(post) {
const WORDS_PER_MINUTE = 200;
const regex = /\w+/g;
const wordCount = post.match(regex)?.length || 0;
return Math.ceil(wordCount / WORDS_PER_MINUTE);
}
How does it work?
We create a readingTime
function, with a post
parameter that would be the text we want to determine the reading time for.
function readingTime(post) {}
People read approximately between 200 and 250 words per minute, so we set a reference variable.
const WORDS_PER_MINUTE = 200;
The trick to finding the words is to use Regex
.
const regex = /\w+/g;
Using the match method, we identify how many words match the regex. Finally, we add the ||
operator followed by a 0
in case no matches are found.
const wordCount = post.match(regex)?.length || 0;
We calculate the reading time by dividing the words found by the words per minute.
wordCount / WORDS_PER_MINUTE;
Then, using Math.ceil(), we get the approximate value:
function readingTime(post) {
const WORDS_PER_MINUTE = 200;
const regex = /\w+/g;
const wordCount = post.match(regex)?.length || 0;
return Math.ceil(wordCount / WORDS_PER_MINUTE);
}
const result = readingTime('Mi tiempo de lectura es de 1 min aprox.');
console.log(result); // resultado: 1
If you want a more approximate value, you can replace Math.ceil with Math.floor, Math.round, or Math.trunc depending on your needs.