00 Votes

JavaScript: Count words in a string

Tip by Progger99 | Last update on 2020-09-03 | Created on 2012-04-16

Here is a little tip, how to quickly and easily determine the number of words in a string with JavaScript:

var str = 'These are some words.';
 
var c = str.split(' ').length;
 
alert("The string consists of " + c + " words.");

We simply separate the string with split() at its spaces. After that, in the fields of the resulting array all words of the sentence are set individually as an element, so that the length if this array is the number of words in the sentence.

Note: Works only, of course, if the words are actually separated by spaces. Double spaces or special characters can falsify the result.

ReplyPositiveNegative
00 Votes

Really very, very ingenious solution. Didn't think that it would be so easy and quick and that str.split(' ') .length would be enough to determine the length. I would have started doing some loops now!
2012-04-17 at 20:24

ReplyPositive Negative
Reply

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.