Categories
JavaScript Answers

How to count words in string with JavaScript?

Spread the love

Sometimes, we want to count words in string with JavaScript.

In this article, we’ll look at how to count words in string with JavaScript.

How to count words in string with JavaScript?

To count words in string with JavaScript, we can use the string split method.

For instance, we write

const numWords = string.split(/\s+/).length;

to call string.split with the /\s+/ regex to split the string string by the spaces.

It returns an array with the split strings.

So we get the number of words in the string with the length property.

Conclusion

To count words in string with JavaScript, we can use the string split method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *