Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Count Words of a String

JavaScript Program to Count Words of a String

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));


Output

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));


Output

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 (' ') and check is false. This means a new word is starting.
    • Increment count to count this new word.
    • Set check to true to indicate that the loop is inside a word.
  • If the current character is a space (' '), it indicates the end of a word.
    • Set check to false to indicate that the loop is not inside a word.
  • 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));


Output

Word count: 4
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments