Can't add the article reading time for richcontent in wix CMS

Question:
I can’t add article reading time for richcontent in Wix Studio.

Product:
[Studio Editor

I’m trying to add article reading time for dynamic page with velo code that works for richcontent like in the wix blog app. But the reading time changed to (Nan) while I count the richcontent
Code example I’m using:

$w.onReady(function () {
    $w("#dynamicDataset").onReady(() => {
 
        let itemObj = $w("#dynamicDataset").getCurrentItem();
 
        const post = itemObj.title;
 
        const avgWordsPerMin = 250;
 
        setReadingTime();
 
        function setReadingTime() {
 
            let count = getWordCount();
            let time = Math.ceil(count / avgWordsPerMin);
 
            $w("#readingTime").text = time + " min read";
 
        }
 
        function getWordCount() {
            return post.length;
        }
    });
});

the code is from the guy in forum.
(I want to achieve the blog post dynamic pages that has reading article to make users improve their time management.)

I think this has to do with the fact that rich text is returned with HTML formatting, not in plain text. A workaround would be to have a field in your CMS collection called “Plain Text” or “Word Count” and paste your exact text into that field without any formatting. Then you would modify you code slightly to return the word count. You can keep the rich text title field connected to your page element.

//with a field labelled "plainText" as an example
$w.onReady(function () {
    $w(“#dynamicDataset”).onReady( () => {
       let itemObj = $w("#dynamicDataset").getCurrentItem();
       let plain_text = itemObj.plainText;
       let avgWordsPerMin = 250;
       let count = plain_text.length;
       let time = Math.ceil(count / avgWordsPerMin);
       $w("#readingTime").text = time.toFixed(0) + " min read";
   });
});

//Your code can be simplified to the above. No need for the function declarations.
1 Like

It works with plain text and paragraph but only not working with richcontent

If you don’t want to add a new field, you would need to strip the article rich text of its html formatting before getting the word count.

$w.onReady(function () {
    $w(“#dynamicDataset”).onReady( () => {
       let itemObj = $w("#dynamicDataset").getCurrentItem();
       let plain_text = itemObj.title.replace(/<[^>]*>?/gm, '');
       let avgWordsPerMin = 250;
       let count = plain_text.length;
       let time = Math.ceil(count / avgWordsPerMin);
       $w("#readingTime").text = time.toFixed(0) + " min read";
   });
});

Hope that helps!

Thank you so much for the Help. Maybe using the text to reading time converter before adding into rich text would be help better for admins and instructors to understand the steps much better. i would try this code in next project.