DEV Community

Estimate the read time of an article without any library in JavaScript.

Lennox Charles on March 01, 2024

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 l...
Collapse
 
fpaghar profile image
Fatemeh Paghar

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:

function estimateReadTime(text, wordsPerMinute = 200) {
  const htmlTagRegExp = /<\/?[^>]+(>|$)/g;
  const textWithoutHtml = text.replace(htmlTagRegExp, '');

  const wordMatchRegExp = /[^\s]+/g;
  const words = textWithoutHtml.matchAll(wordMatchRegExp);

  const wordCount = [...words].length;
  const readTime = Math.round(wordCount / wordsPerMinute);

  return readTime;
}

// Example usage with default speed (200 words per minute)
const defaultReadTime = estimateReadTime("Your article content here...");

// Example usage with custom speed (e.g., 250 words per minute)
const customReadTime = estimateReadTime("Your article content here...", 250);

Enter fullscreen mode Exit fullscreen mode

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! šŸŒŸšŸ“–šŸŽØ