Count the Words or Spaces in a String in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
6 min

banner

# 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
  4. Count the Spaces in a String in 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

count words in string

The code for this article is available on GitHub

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
The code for this article is available on GitHub
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.

# Table of Contents

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

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

This is a three-step process:

  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

count words in string using string trim

The code for this article is available on GitHub

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 cheat sheet by MDN.

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

# Table of Contents

  1. Count the words in a TextArea element using JavaScript
  2. Count the Spaces in a String in JavaScript

# 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.

# Count the Spaces in a String in JavaScript

To count the spaces in a string:

  1. Use the split() method to split the string into an array on each space.
  2. Subtract 1 from the array's length.
  3. The result will be the number of spaces in the string.
index.js
const str = 'bobby hadz com'; const spacesCount = str.split(' ').length - 1; console.log(spacesCount); // ๐Ÿ‘‰๏ธ 2

count spaces in string

The code for this article is available on GitHub

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

The method returns an array of substrings.

index.js
const str = 'bobby hadz com'; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(str.split(' '));

We have to subtract 1 from the array's length to get the number of spaces in the string because the space is the separator.

index.js
const str = 'bobby hadz com'; const spacesCount = str.split(' ').length - 1; console.log(spacesCount); // ๐Ÿ‘‰๏ธ 2

If you have to do this often, define a reusable function.

index.js
function countSpaces(str) { return str.split(' ').length - 1; } const str = 'bobby hadz com'; console.log(countSpaces(str)); // ๐Ÿ‘‰๏ธ 2

define reusable function

The code for this article is available on GitHub

The countSpaces function takes a string as a parameter and returns the number of spaces in the string.

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

# Count the Spaces in a String using String.replaceAll()

This is a three-step process:

  1. Use the length property to get the string's length.
  2. Use the replaceAll() method to remove all spaces from the string.
  3. Subtract the length of the new string from the length of the original string.
index.js
const str = 'bobby hadz com'; const spacesCount = str.length - str.replaceAll(' ', '').length; console.log(spacesCount); // ๐Ÿ‘‰๏ธ 2

count spaces in string using replaceall

The code for this article is available on GitHub

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.
The last step is to subtract the length of the string that contains no spaces from the length of the string that contains spaces.

The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

You can also define a reusable function.

index.js
function countSpaces(str) { return str.length - str.replaceAll(' ', '').length; } const str = 'bobby hadz com'; console.log(countSpaces(str)); // ๐Ÿ‘‰๏ธ 2

The function takes a string and returns the number of spaces in the string.

# Count the Spaces in a String using String.match()

This is a two-step process:

  1. Use the String.match() method to match each space in the string.
  2. Access the length property on the array.
index.js
function countSpaces(str) { return str.match(/\s/g)?.length || 0; } console.log(countSpaces('bobby hadz com')); // ๐Ÿ‘‰๏ธ 2 console.log(countSpaces('abc')); // ๐Ÿ‘‰๏ธ 0 console.log(countSpaces('a bc')); // ๐Ÿ‘‰๏ธ 1

count the spaces in string using string match

The code for this article is available on GitHub

The String.match method matches a string against a regular expression.

index.js
const str = 'bobby hadz com'; // ๐Ÿ‘‡๏ธ [ ' ', ' ' ] console.log(str.match(/\s/g));

The method returns an array containing the matches (if any) or null if no matches are found.

We used the optional chaining (?.) operator to short-circuit if the method returned null.

index.js
function countSpaces(str) { return str.match(/\s/g)?.length || 0; }

The optional chaining (?.) operator short-circuits and returns undefined if the value to the left is nullish (null or undefined).

If the String.match() method returns null, the function returns 0 as there are no spaces in the string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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 ยฉ 2024 Borislav Hadzhiev