Skip to content

Instantly share code, notes, and snippets.

@bobmonsour
Last active April 1, 2023 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobmonsour/53ea41c50bec94be394a9314858dad1d to your computer and use it in GitHub Desktop.
Save bobmonsour/53ea41c50bec94be394a9314858dad1d to your computer and use it in GitHub Desktop.
This code can be used as an eleventy filter to create the reading time (in minutes) of a piece of content.
/*
* Calculate the reading time, in minutes, of a post
*
* Assumptions:
* - average reading time is 240 words per minute
* source: https://bit.ly/3HCogSr, "Most Comprehensive
* Review To Date Finds The Average Person’s Reading
* Speed Is Slower Than Previously Thought"
*
* Output:
* - reading time is rounded to the nearest minute
* - in the case of less than 1 minute, reading time is
* displayed as "less than a minute"
*
* @param {String} text
*/
module.exports = function (text) {
var content = new String(text);
const speed = 240; // reading speed in words per minute
// remove all html elements
var re = /(&lt;.*?&gt;)|(<[^>]+>)/gi;
var plain = content.replace(re, "");
// replace all newlines and 's with spaces
var plain = plain.replace(/\s+|'s/g, " ");
// create array of all the words in the post & count them
var words = plain.split(" ");
var count = words.length;
// calculate the reading time
var readingTime = Math.round(count / speed);
if (readingTime === 0) {
return "Less than 1 minute to read";
} else if (readingTime === 1) {
return "1 minute to read";
} else {
return readingTime + " minutes to read";
}
};
@bobmonsour
Copy link
Author

bobmonsour commented Apr 1, 2023

Cool. Thanks for the link to regex101. Looks very handy. I'm going to make an update to my Calculating blog using your suggestions (at some point). Right now, I'm scouring the net for the next issue of The 11ty Bundler. I am thinking that if I continue to generate the Bundler, it will probably turn into its own website. I broke down and bought the 11tybundler.com domain yesterday. Not that that necessarily signals commitment as I have a handful of other unused domains that started as ideas in my head. At least with this one, I've already started something that could make more sense for me to head down that path. What I like about the idea is that it will give me more reasons to keep learning about Eleventy, JS, and CSS.

@Aankhen
Copy link

Aankhen commented Apr 1, 2023

Sounds like a great idea to me. I look forward to reading more, if you do put together more issues (so to speak). 😊

@bobmonsour
Copy link
Author

This gist has been updated with the help of @Aankhen. Many thanks. The resulting word counts are comparable to the earlier regex I used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment