Count words for a textarea field using javascript

Count words for a textarea field using javascript

<!DOCTYPE html>
<html>
<body style="text-align: center">
    <h1 style="color: lightblue">Word count</h1>

    
<p>Type in the textarea and display word count</p>


    <textarea id="word" rows="10" cols="60"> </textarea>
    <br /><br />

    <p>
    Word Count:
    <span id="show">0</span>
    </p>


    <script>
    document
        .querySelector("#word")
        .addEventListener("keyup", function countWord() {
        let res = [];
        let str = this.value.replace(/[\t\n\r\.\?\!]/gm, " ").split(" ");
        str.map((s) => {
            let trimStr = s.trim();
            if (trimStr.length > 0) {
            res.push(trimStr);
            }
        });
        document.querySelector("#show").innerText = res.length;
        });
    </script>
</body>
</html>

Leave a Comment

Your email address will not be published. Required fields are marked *