JavaScript - How to Count Words of a String?
Last Updated : 26 Nov, 2024
Here are the various methods to count words of a string in JavaScript.
1. Using split() Method
The simplest and most common approach is to use the split() method to divide the string into an array of words and count the length of the array.
JavaScript const count = (s) => s.trim().split(/\s+/).length; const s = "Hello, this is a simple test."; console.log(count(s));
- Trim the leading and trailing spaces with trim().
- Splitting the string using a regular expression /\s+/, which matches one or more whitespace characters.
2. Using Regular Expressions
You can use a regular expression to match all words in a string and count the matches.
JavaScript const count = (s) => (s.match(/\b\w+\b/g) || []).length; const s = "Hello, this is a simple test."; console.log(count(s));
The regex /\b\w+\b/g matches word boundaries (\b) and considers sequences of alphanumeric characters as words.
3. Using reduce() Method
This approach splits the string into an array of words and uses reduce() to count them.
JavaScript const count = (s) => s.trim().split(/\s+/).reduce((count) => count + 1, 0); const s = "Hello, this is a simple test."; console.log(count(s));
This method is useful if you want to perform additional operations during word counting.
4. Using a Loop
You can iterate through the string manually, counting words whenever a whitespace or end of the string is encountered.
JavaScript const count = (s) => { let c = 0; let inWord = false; for (const char of s) { if (/\s/.test(char)) { inWord = false; } else if (!inWord) { inWord = true; c++; } } return c; }; const s = "Hello, this is a simple test."; console.log(count(s));
This approach provides full control over the word counting process.
5. Using matchAll() Method
The matchAll() method offers a clean way to count words by matching them with a regular expression.
JavaScript const count = (s) => [...s.matchAll(/\b\w+\b/g)].length; const s = "Hello, this is a simple test."; console.log(count(s));
This is a modern and concise way to count word matches using an iterator.
6. Using Array.from() and filter() Methods
By splitting the string into characters, you can use Array.from() with filtering to count words.
JavaScript const count = (s) => Array.from(s.split(/\s+/).filter(Boolean)).length; const s = "Hello, this is a simple test."; console.log(count(s));
This approach is useful if you want to remove empty strings during processing.
Which Approach Should You Use?
Approach | When to Use |
---|
Using split() | Best for simplicity and common use cases. |
Using Regular Expressions | Ideal for precise control over what is considered a word. |
Using reduce() | Use when combining word counting with additional operations. |
Using a Loop | Best for custom logic or low-level string processing. |
Using matchAll() | Modern and concise approach for counting regex matches. |
Using Array.from() and Filter | Use when filtering or processing split results is required. |
The split() and regular expression methods are the most commonly used and efficient.
Similar Reads
JavaScript - How To Count String Occurrence in String? Here are the various methods to count string occurrence in a string using JavaScript.1. Using match() Method (Common Approach)The match() method is a simple and effective way to count occurrences using a regular expression. It returns an array of all matches, and the length of the array gives the co
3 min read
How to make a word count in textarea using JavaScript ? Counting words may be useful in scenarios where the user is recommended to enter a certain number of words and the word counter can keep track of the same. Below are approaches to make a word count in textarea using JavaScript:Table of Content Calculating the number of spaces present in the textSepa
4 min read
How to count the number of words in a string in PHP ? Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches:Table of ContentUsing str_word_count() MethodUsing trim(), preg_replace(), count() and explode() method. Using trim(), substr_count(), and
4 min read
JavaScript Program to Count the Occurrences of Each Character Here are the various methods to count the occurrences of each characterUsing JavaScript ObjectThis is the most simple and widely used approach. A plain JavaScript object (obj) stores characters as keys and their occurrences as values.JavaScriptconst count = (s) => { const obj = {}; for (const cha
3 min read
JavaScript Program to Calculate the Frequency of Each Word in the Given String Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript. Example:Input:"geeks for geeks is for geeks"Output:"geeks": 3 , "for": 2 , "is": 1 Below are the approaches for calculating the Frequency of Each Word in the Given String using JavaScript: Table
3 min read
JavaScript Program to Count the Occurrences of a Specific Character in a String In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript. Example: Input : S = âgeeksforgeeksâ and c = âeâOutput : 4Explanation: âeâ appears four times in str
3 min read