aboutDavid's website

Calculating Read time in JavaScript

This is a very simple task. First, we need a sentence to try this out. Let's use "The quick brown fox jumps over the lazy dog". A few thing we need to know is:

So, we have to split the text every 5 letters and divide it by 225 WPM. This can easily be done with JavaScript:

"The quick brown fox jumps over the lazy dog.".match(/.{1,5}/g).length/225;

Which should return a value of 0.04. So are we done? No. We also need make it human readable. First we need to round to the nearest whole number by using Math.round() :

Math.round("The quick brown fox jumps over the lazy dog.".match(/.{1,5}/g).length/225);

Which should return 0. Now we are almost done. Let's make it human readable. We can give it summaries using if/else statements.

Lets use:

as statements.

var rt = Math.round("The quick brown fox jumps over the lazy dog.".match(/.{1,5}/g).length/225);
if (rt <= 0) {
rt = "Less than a minute read."
} else if (rt === 1){
rt = `${rt} min read.`
} else if (isNaN(rt)){
rt = "Failed to calculate readtime!"
} else {
rt = "Failed to calculate readtime!"
}

which returns Less than a minute read.

Let's make it ready for "production" by wrapping it around a function and compressing it using JScompress. I put the source code on P2Pbin, which you can find here.