function calcReadingTime(text) { // 1: return `0` for empty text if (text === '') { return 0; } // 2: define average reading speed in words per minute const wordsPerMin = 200; // 3: strip any HTML tags from text const textOnly = text.replace(/(<([^>]+)>)/ig, ''); // 4: split text into words and filter empty strings (from space before/after HTML tags) const words = textOnly.split(' ').filter((word) => word !== ''); // 5: count words in text const wordsCount = words.length; // 6: calculate reading time return Math.ceil(wordsCount / wordsPerMin); }
const text = ` <p> Convallis lectus, accumsan ad egestas blandit sollicitudin. Dictumst parturient ut nam fusce erat sociosqu. Fusce ut est morbi eleifend maecenas aptent hendrerit sagittis eu. Tempus commodo, taciti dictumst netus velit. Eros integer semper porttitor proin suspendisse cum erat nostra dictum ipsum praesent. Nibh velit proin viverra, risus eu. Semper semper parturient lobortis dapibus ridiculus orci. </p> <p> Sociis suspendisse varius ullamcorper euismod, curabitur semper placerat scelerisque cras litora tristique inceptos! Dis orci sem ad tellus curabitur mi! Ultrices varius sagittis felis hac placerat purus erat morbi vestibulum magnis dictum. Convallis gravida cras in cursus erat vestibulum congue. Cubilia iaculis tellus vulputate iaculis cursus lorem phasellus. Mus vestibulum etiam nisi elementum libero. Proin class id eget sodales? </p> <p> Sed venenatis, orci enim felis sodales venenatis. Vulputate ante aptent leo fames fames elit duis viverra. Feugiat sit bibendum in id aliquet. Egestas tempus mauris turpis sit, ridiculus ultrices ad aptent. Ut feugiat, arcu mattis ad parturient cras scelerisque justo habitasse tempor. Risus iaculis mauris adipiscing aenean. Urna accumsan magna dis lectus lobortis mattis tincidunt proin iaculis. Luctus euismod posuere amet a odio nascetur inceptos. Quisque ridiculus sit phasellus cum odio tincidunt sapien mi aliquet blandit. Pharetra? </p> `; console.log(`${calcReadingTime(text)} min(s)`); // '1 min(s)'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.