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.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
jQuery: Count characters from multiple input fields
Tip | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
MySQL: Combine full text search with LIKE search for words with 3 letters
Tutorial | 2 Comments
JavaScript: Show and hide HTML area by clicking a link
Tutorial | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
jQuery: Scroll up and down with and without JavaScript
Tip | 0 Comments
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.
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