Recently I needed to find a way to count the words in a paragraph and chop it if it’s too long. There’s a quick way to do this in JavaScript using the native split
method.
Working on the Node.js command line gives you a nice way to see how this works and a little of how JavaScript treats strings.
Enter a long string into a variable and you then get access to string properties like length, which will here mean the character length including spaces.
> sentence = "my long sentence of words and words and more more words" 'my long sentence of words and words and more more words' > sentence.length 55
Now you can use the split
method to split this string at every blank space, entering an empty space as the parameter to split
.
> sentence.split(' '); [ 'my', 'long', 'sentence', 'of', 'words', 'and', 'words', 'and', 'more', 'more', 'words' ]
This returns an array with the split up sentence in it, chopped into individual words.
So if you split first, then call length, now you get your word length.
> sentence.split(' ').length 11