JavaScript - How to Count Words of a String? Last Updated : 26 Nov, 2024 Comments Improve Suggest changes Like Article Like Report Here are the various methods to count words of a string in JavaScript.1. Using split() MethodThe 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)); Output6 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 ExpressionsYou 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)); Output6 The regex /\b\w+\b/g matches word boundaries (\b) and considers sequences of alphanumeric characters as words.3. Using reduce() MethodThis 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)); Output6 This method is useful if you want to perform additional operations during word counting.4. Using a LoopYou 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)); Output6 This approach provides full control over the word counting process.5. Using matchAll() MethodThe 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() MethodsBy 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)); Output6 This approach is useful if you want to remove empty strings during processing.Which Approach Should You Use?ApproachWhen to UseUsing split()Best for simplicity and common use cases.Using Regular ExpressionsIdeal for precise control over what is considered a word.Using reduce()Use when combining word counting with additional operations.Using a LoopBest for custom logic or low-level string processing.Using matchAll()Modern and concise approach for counting regex matches.Using Array.from() and FilterUse when filtering or processing split results is required.The split() and regular expression methods are the most commonly used and efficient. Comment More infoAdvertise with us Next Article JavaScript - How to Count Words of a String? M mansigeekso9ii Follow Improve Article Tags : JavaScript Web Technologies javascript-string JavaScript-DSA JavaScript-Questions +1 More 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 Work with 'word-count' Module in Node.js ? The word-count module is a lightweight and straightforward Node.js library designed to count words in a given text or string. It provides a convenient way to analyze text content programmatically, which can be useful in various applications such as text processing, analytics, and content management. 3 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 Java program to count the characters in each word in a given sentence Write a Java program to count the characters in each word in a given sentence? Examples: Input : geeks for geeksOutput :geeks->5for->3geeks->5 Recommended: Please solve it on PRACTICE first, before moving on to the solution. Approach:Here we have to find out number of words in a sentence an 3 min read Count a Group of Words in a String Using Regex in Java Regular Expression is a powerful approach in Java for searching, Manipulating, and matching patterns with specific pattern requirements. In this article, we will learn to count a group of words in a string using regex. First I explain count a group of words in a string using regex as per requirement 4 min read Program to count the number of words in a sentence Write a program to count the number of words in a given sentence. A word is defined as a sequence of characters separated by spaces. Examples: Input: "The quick brown fox"Output: 4Explanation: The sentence has four words - "The", "quick", "brown", "fox". Input: "The quick brown fox"Output: 4Explanat 3 min read Like