How to count the words in a String in JavaScript

avatar

Borislav Hadzhiev

3 min

banner

Photo from Unsplash

Table of Contents #

  1. Count the words in a String using JavaScript
  2. Count the words in a String using String.trim()
  3. Count the words in a TextArea element using JavaScript

Count the words in a String using JavaScript #

To count the words in a string:

  1. Use the String.split() method to split the string into an array of words.
  2. Access the length property on the array.
  3. The length property will return the number of words in the string.
index.js
function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } console.log(countWords('bobby hadz com')); // ๐Ÿ‘‰๏ธ 3 console.log(countWords('This is a long string')); // ๐Ÿ‘‰๏ธ 5

We created a reusable function that takes a string as a parameter and returns the number of words in the string.

We used the String.split() method to split the string on each space.

The method returns an array containing the words in the string.

index.js
// ๐Ÿ‘‡๏ธ ['hello', 'world'] console.log('hello world'.split(' ')); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log('bobby hadz com'.split(' '));
However, if the string contains multiple spaces next to one another, this approach would split on the first space and would then add empty strings to the array.
index.js
// ๐Ÿ‘‡๏ธ ['hello', '', 'world'] console.log('hello world'.split(' ')); // ๐Ÿ‘‡๏ธ ['one', '', 'two', '', 'three'] console.log('one two three'.split(' '));

We can use the Array.filter method to make sure we don't count empty strings as words.

The filter method enables us to remove the empty strings before accessing the length property on the array.

The function we passed to the filter() method gets called with each element in the array.

index.js
function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } console.log(countWords('bobby hadz com')); // ๐Ÿ‘‰๏ธ 3 console.log(countWords('This is a long string')); // ๐Ÿ‘‰๏ธ 5
If the function returns a truthy value, the element gets added to the new array that the filter() method returns.

We check if each element is NOT equal to an empty string and return the result.

index.js
const arr = ['one', '', 'two', '']; const filtered = arr.filter(element => element !== ''); // ๐Ÿ‘‡๏ธ ['one', 'two'] console.log(filtered);

The last step is to access the length property on the array to get the word count.

Alternatively, you can use the String.trim() method.

Count the words in a String using String.trim() #

To count the words in a string:

  1. Use the String.trim() method to trim the string.
  2. Use the String.split() method to split the string by one or more spaces.
  3. Access the length property on the result.
index.js
function countWords(str) { return str.trim().split(/\s+/).length; } console.log(countWords('bobby hadz com')); // ๐Ÿ‘‰๏ธ 3 console.log(countWords('This is a long string')); // ๐Ÿ‘‰๏ธ 5

We used the String.trim() method to remove any leading and trailing whitespace from the string.

index.js
console.dir(' abc '.trim()); // ๐Ÿ‘‰๏ธ "abc"

The next step is to use the String.split() method to split the string by one or more consecutive spaces.

We passed a regular expression to the String.split() method.

index.js
function countWords(str) { return str.trim().split(/\s+/).length; }

The forward slashes / / mark the beginning and end of the regular expression.

The \s special character matches spaces, tabs and newlines.

The plus + matches the preceding item one or more times (spaces).

In its entirety, the regular expression matches one or more consecutive spaces.

This way, we can be sure that we won't get multiple words if the string contains multiple spaces next to one another.

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

Count the words in a TextArea element using JavaScript #

To count the words in a textarea element:

  1. Access the value property on the textarea element.
  2. Split the value on each space.
  3. Use the length property to get the word count.

Here is the HTML for the example in the article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <textarea id="textarea" cols="30" rows="10"></textarea> <p> Number of words: <span id="word-count"></span> </p> <button id="btn">Count words</button> <script type="module" src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } const button = document.getElementById('btn'); button.addEventListener('click', () => { const textarea = document.getElementById('textarea'); const wordCount = countWords(textarea.value); console.log(wordCount); const span = document.getElementById('word-count'); span.innerHTML = wordCount; });

count words textarea

Every time the button is clicked, we log how many words are written in the textarea element and show the result using a span element.

We added a click event listener to the button element, so every time it is clicked, a function is invoked.

We used the value property to get the value of the textarea element and used the previous function to get the word count.

The last step is to write the result to the screen by using the innerHTML property on the span element.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev