How to Count the Number of Words in JavaScript?

Estimated read time 1 min read

To count the number of words in a string in JavaScript, you can split the string into an array of words using the split() method and then use the length property to determine the number of elements in the array. Here’s an example:

function countWords(str) {
  return str.split(" ").length;
}

const sentence = "Count the number of words in this sentence.";
const numWords = countWords(sentence);
console.log(`The number of words in the sentence is: ${numWords}.`);

In the example above, the split() method is used to split the string sentence into an array of words using a space as a separator. The length property is then used to determine the number of elements in the array, which represents the number of words in the string. The result is logged to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply