How to Count Words and Characters in JavaScript
Tags: javascript, beginners, tutorial, productivity
Published: 2023-01-18 23:11:56

Most if not all developers have used some sort of character counter online to validate SEO, or to just see how many characters a string has. You can do this on your own website or internal tooling. It is simple JavaScript and can have a wide variety of uses throughout your career as a JavaScript developer.

In this tutorial, we'll be exploring how to count words and characters in JavaScript. We'll be using the String constructor and the length property to get the word and character count for a string.

## View This On YouTube
{% youtube Q9d_AZXUZu4 %}

## File Structure
```
index.html
/sass
     style.scss
/js
     Count.js
/css (generated by Sass)
   style.css
   style.min.css
```

## Our HTML

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Character and Word Counter</title>
    <link rel="stylesheet" href="/css/style.min.css">
</head>
<body>
    <div class="main">
        <h1>Count Your</h1>
        <h2>Words and Characters</h2>
        <div class="card">
            Words
            <span class="word-count">0</span>
        </div>
        <div class="card">
            Characters
            <span class="character-count">0</span>
        </div>
        <textarea class="count__textarea">This is sample text that should be counted on load.</textarea>
        You've written <span class="word-count">0</span> words and <span class="character-count">0</span> characters.
    </div>
    <script src="/js/Count.js"></script>
</body>
</html>
```

The basic HTML is simple and has a textarea and different spans (2 displayed as cards, and 2 inline texts) to show the counts.

## Our Count JS Class

```js
class Count {
    constructor() {
        this.textArea = document.querySelector(".count__textarea")
        this.wordCount = document.querySelectorAll(".word-count")
        this.charCount = document.querySelectorAll(".character-count")
        /*
        bind(this) is used to make sure that the this keyword inside the updateCount method refers to the Count class
        */
        window.addEventListener("load", this.updateCount.bind(this))
        this.textArea.addEventListener("input", this.updateCount.bind(this))
    }

    /**
     * trim() removes whitespace from both sides of a string
     * if the value is empty, return 0
     * split() splits a string into an array of substrings, and returns the new array
     * @returns {number} the number of words in the textarea
     */
    countWords() {
        const value = this.textArea.value.trim()
        if(!value) return 0
        return value.split(/\s+/).length
    }

    /**
     * length returns the length of a string
     * @returns {number} the number of characters in the textarea
     */
    countChars() {
        return this.textArea.value.length 
    }

    /**
     * update the word and character count
     * forEach() calls a function once for each element in an array, in order
     * toString() converts a number to a string
     * @returns {void}
     */
    updateCount() {
        const numWords = this.countWords()
        const numChars = this.countChars()

        this.wordCount.forEach((wordCount) => {
            wordCount.textContent = numWords.toString(10)
        })

        this.charCount.forEach((charCount) => {
            charCount.textContent = numChars.toString(10)
        })
    }
}

new Count() // create a new instance of the Count class
```

This is a really easy-to-use and simple class that gets the spans and textarea. Once it has those it either listens on page load or when the textarea input is changed.

Once one of those events happens, it simply counts the words and characters and then displays the count in the spans we created in the HTML.

## Sample Styles

I created a sample style in Sass. You don't have to use it for your project, but it basically displays the cards and makes the inline text spans bold. You can copy the following to make it look just like my tutorial.

```css
@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap');

$font-family: 'Open Sans', sans-serif;
$font-size:16px;
$primary-color: #38a4ef;

body {
    font-size: $font-size;
    font-family: $font-family;
    width:100%;
    min-height:100vh;
    background-color:$primary-color;
    padding:0;
    margin:0;
    color:#fff;
    overflow:hidden;
    .main {
        width:60%;
        text-align:center;
        margin:10% auto;
        h1,h2 {
            margin:0;
            padding:0;
        }
        .card {
            background-color:#fff;
            padding:3rem;
            border-radius: 5px;
            width:200px;
            display:inline-block;
            margin:1rem;
            color:#333;
            box-shadow: 15px 15px 0px 0px rgba(0,0,0,.2);
            span {
                font-size: 2rem;
                display:block;
            }
        }
        textarea {
            display:block;
            width:calc(100% - 2rem);
            height:200px;
            border:0;
            margin:1rem 0;
            padding:1rem;
            font-size: $font-size;
            border-radius: 5px;
            &:focus {
                outline:none;
            }
        }
        .word-count, .character-count {
            font-weight: bold;
        }
    }
}
```

## Conclusion

There you go. With a few lines of code, you can create your own internal character and word counters using vanilla JS. I hope this helps. Let me know if you have any questions.

Read more articles on [DevDrawer](https://thedevdrawer.com)