DEV Community

Cover image for How to Count Words and Characters in JavaScript Without a Library
sam khan
sam khan

Posted on

How to Count Words and Characters in JavaScript Without a Library

Counting words and characters is a common feature in writing tools, form fields, blog editors, and social media applications.

JavaScript makes it possible to build a simple text counter without installing any external libraries. In this tutorial, we'll create a word and character counter that updates as the user types.

We'll also look at how spaces, line breaks, and emoji affect the results.

1. Create the HTML

Start with a textarea where users can enter their text. Below it, add three elements to display the results.

<textarea id="textInput" rows="8" placeholder="Type or paste your text here..."></textarea>

<p>Words: <span id="wordCount">0</span></p>
<p>Characters: <span id="characterCount">0</span></p>
<p>Characters without spaces: <span id="noSpaceCount">0</span></p>
Enter fullscreen mode Exit fullscreen mode

The textarea provides the input, while the three spans display the calculated counts.

2. Count Words Using JavaScript

A simple way to count words is to trim the text and split it using whitespace.

function countWords(text) {
  const trimmed = text.trim();

  if (trimmed === "") {
    return 0;
  }

  return trimmed.split(/\s+/).length;
}
Enter fullscreen mode Exit fullscreen mode

The trim() method removes whitespace from the beginning and end of the text.

The regular expression /\s+/ splits the text wherever it finds one or more whitespace characters, including spaces, tabs, and line breaks.

This is a useful approach for a basic English-language word counter. More advanced counters may need language-specific word segmentation.

3. Count Characters

JavaScript provides the length property to measure the length of a string.

function countCharacters(text) {
  return text.length;
}
Enter fullscreen mode Exit fullscreen mode

For ordinary English text, this produces the expected character count in most cases.

However, JavaScript string length counts UTF-16 code units. Some characters, including many emoji, use more than one code unit.

If you want to count Unicode code points instead, you can use:

function countCodePoints(text) {
  return Array.from(text).length;
}
Enter fullscreen mode Exit fullscreen mode

Even this method does not always count what a person sees as one character. Some emoji sequences and combined characters contain multiple code points.

4. Count Characters Without Spaces

Sometimes you need to calculate the number of characters while excluding whitespace.

function countWithoutSpaces(text) {
  return text.replace(/\s/g, "").length;
}
Enter fullscreen mode Exit fullscreen mode

This function removes whitespace before calculating the string length.

It excludes spaces, tabs, and line breaks. If you want to exclude only ordinary spaces, use text.replace(/ /g, "") instead.

5. Update the Counter as the User Types

Now connect the JavaScript functions to the HTML elements.

const textInput = document.getElementById("textInput");
const wordCount = document.getElementById("wordCount");
const characterCount = document.getElementById("characterCount");
const noSpaceCount = document.getElementById("noSpaceCount");

function updateCounts() {
  const text = textInput.value;

  wordCount.textContent = countWords(text);
  characterCount.textContent = countCharacters(text);
  noSpaceCount.textContent = countWithoutSpaces(text);
}

textInput.addEventListener("input", updateCounts);

updateCounts();
Enter fullscreen mode Exit fullscreen mode

The input event runs whenever the textarea's value changes through normal user input, including typing, pasting, and deleting text.

This keeps the displayed counts up to date without requiring a submit button.

6. Test the Word and Character Counter

Try entering the following text:

JavaScript makes text analysis easy.
Enter fullscreen mode Exit fullscreen mode

The basic counter should display:

  • Words: 5
  • Characters: 36
  • Characters without spaces: 32

Next, try entering multiple spaces, blank lines, and emoji to see how the counting functions behave.

Testing different inputs helps you understand how JavaScript handles text and whitespace.

7. Try an Online Text Counter

Building your own counter is a useful way to learn JavaScript string manipulation and DOM events.

For everyday writing, you can also use the TextNivo Word Counter to analyze text without writing code.

If you already know the number of characters but need to estimate the equivalent number of words, the Characters to Words Converter is designed for that different task.

Conclusion

You've built a simple word and character counter using plain JavaScript.

The project demonstrates how to work with strings, regular expressions, DOM elements, and input events.

You can extend it by adding a reading-time estimator, a character-limit indicator, or a sentence counter.

For more JavaScript text-processing examples, explore the TextNivo Text Utilities project on GitHub.

Top comments (0)