Split a string using whitespace in Javascript?

dokondr picture dokondr · Feb 22, 2012 · Viewed 25.5k times · Source

I need a tokenizer that given a string with arbitrary white-space among words will create an array of words without empty sub-strings.

For example, given a string:

" I dont know what you mean by glory Alice said."

I use:

str2.split(" ")

This also returns empty sub-strings:

["", "I", "dont", "know", "what", "you", "mean", "by", "glory", "", "Alice", "said."]

How to filter out empty strings from an array?

Answer

Daff picture Daff · Feb 22, 2012

You probably don't even need to filter, just split using this Regular Expression:

"   I dont know what you mean by glory Alice said.".split(/\b\s+/)