5 Effective Ways to Count Words in a JavaScript String

5 Effective Ways to Count Words in a JavaScript String

Counting words is a common task in the programming world. For example, to find out how many words are in a sentence, to determine the length of the text, to analyze SEO titles or descriptions, or for content processing, etc. In today's blog, I will discuss how to solve the above problem easily using JavaScript and find the number of words in a string with detailed code.


function countWords(str) {
    // Extra spaces have been removed
    str = str.trim();
    // If the string is empty, there are no words
    if (str === "") {
      return 0;
    }
    // Split the string by spaces and return the length of the array
    const words = str.split(/\s+/);
    return words.length;
  }
  
// Example
const sentence = "notesaid24 provides best programming tutorial";
console.log(countWords(sentence)); // Output: 5


Explanation:

  • First, the extra spaces at the beginning and end of the string are removed using the trim() method, so that the word count is correct.
  • We use the split(/\s+/) method to split the string according to the space. Here /\s+/ is a regular expression that separates one or more spaces.
  • Then we find the total number of words using the length of the array.


Method 2 –


function countWordsUsingMatch(str) {
  // Trim and remove extra spaces
  str = str.trim();

  // Find words using regular expression
  const words = str.match(/\b\w+\b/g);
  
  // Return 0 if no words are found, otherwise return the total word count
  return words ? words.length : 0;
}

// Example
const sentence = "notesaid24 provides best programming tutorial";
console.log(countWordsUsingMatch(sentence)); // Output: 5


Explanation: /\b\w+\b/g This regular expression separates each word. Here, the beginning and end of each word are marked with \b and each word is marked with \w+.


Method 3 –


function countWordsUsingReduce(str) {
  // Trim and remove extra spaces
  str = str.trim();

  // If the string is empty, return 0
  if (str === "") {
    return 0;
  }

  // Split the string by spaces and count words using reduce
  return str.split(/\s+/).reduce((count, word) => word ? count + 1 : count, 0);
}

// Example
const sentence = "notesaid24 provides best programming tutorial";
console.log(countWordsUsingReduce(sentence)); // Output: 5


Explanation: First, the string is split by spaces, then the JavaScript reduce method is used to loop over each word and count.


Method 4 –


function countWordsUsingLoop(str) {
  // Trim the string to remove extra spaces
  str = str.trim();

  let count = 0;
  let inWord = false;

  // Loop through each character in the string
  for (let i = 0; i < str.length; i++) {
    if (str[i] !== ' ') {
      if (!inWord) {
        count++;
        inWord = true;
      }
    } else {
      inWord = false;
    }
  }

  return count;
}

// Example
const sentence = "notesaid24 provides best programming tutorial";
console.log(countWordsUsingLoop(sentence)); // Output: 5


Explanation: Each word in the string is checked. If there is no space at the beginning of the word, it is counted as a new word and the inWord flag is set to true. When a space is found again, the inWord flag is set to false.


Method 5 –


function countWordsUsingFilter(str) {
  // Split the string by spaces and filter out empty strings, then return the length
  return str.split(' ').filter(word => word !== '').length;
}

// Example
const sentence = "notesaid24 provides best programming tutorial";
console.log(countWordsUsingFilter(sentence)); // Output: 5


Explanation: First, each word is separated using split(' ') and the filter method is used to remove blank words and return the length of the array.

 

Bookmark the website! If you like the post and don't forget to share the post so that your friends don't miss it. Be sure to like and comment so that we can constantly come up with new problems as well as solutions. And if you have any coding-related problems, please let us know in the comment box and we will try to solve them, InshaAllah.

About the author

M A Habib
Hello! I am M A Habib. I am a MERN Stack web developer. Blogging is my hobby and I would like to share my knowledge with everyone. Here I will share every day about education, technology, and Programming. So stay with us and share my page on your so…

Post a Comment