Given the string, the task is to count the words of a string using JavaScript. The words are separated by the following characters: space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a combination of these.
Below are the following approaches through which we can count words in a string using JavaScript:
- Using trim() and split() Methods
- Using Regular Expression and match() Methods
- Using for loop
Count Words of a String using trim() and split() Methods in JavaScript
In this approach, we will use the trim() method to remove and trail the space, and the split() method to split the string by one or more spaces.
Example:
Javascript
function wordsLen(str) { const array = str.trim().split(/\s+/); return array.length; } const str = "Welcome, to the Geeeksforneveropen" ; console.log( "Word count:" ,wordsLen(str)); |
Word count: 4
Count Words of a String using Regular Expression and match() Methods in JavaScript
In this approach, we will use match() method with the regular expression. The JavaScript String match() method is an inbuilt function in JavaScript used to search a string for a match against any regular expression. So match() will return the array which contains all the string which matches any non-whitespace character.
Example:
Javascript
function numberOfWords(str) { const words = str.match(/\S+/g); if (words.length!==0){ return words.length; } else { return 0; } } const str = "Welcome, to the Geeksforneveropen" ; console.log( "Word count:" , numberOfWords(str)); |
Word count: 4
JavaScript Program to Count Words of a String using for loop
In this approach, we will use for loop to iterate over the string .
- We will make two variable “count” for storing the count of words and “check” for tracking the loop is inside the word or not.
- Start a
for
loop to iterate through each character in the input string. - Check if the current character is not a space (
' '
) andcheck
isfalse
. This means a new word is starting.- Increment
count
to count this new word. - Set
check
totrue
to indicate that the loop is inside a word.
- Increment
- If the current character is a space (
' '
), it indicates the end of a word.- Set
check
tofalse
to indicate that the loop is not inside a word.
- Set
- return the count.
Example:
Javascript
function numberOfWords(str) { let count = 0; let check = false ; for (let i = 0; i < str.length; i++) { if (str[i] !== ' ' && !check) { count++; check = true ; } else if (str[i] === ' ' ) { check = false ; } } return count; } const str = "Welcome to the Geeksforneveropen" ; console.log( "Word count:" , numberOfWords(str)); |
Word count: 4