Splitting string by whitespace, without empty elements?

This is the simplest solution IMO. trim() first to get rid of leading/trailing whitespace, then split by whitespace.

function split(str) {
  return str.trim().split(/\s+/);
}

console.log(split('foo bar baz'));
console.log(split('  foo  bar  baz '));

You could simply match all non-space character sequences:

str.match(/[^ ]+/g)

No matter what splitter this always works:

str.split(' ').filter(function(i){return i})
// With ES6
str.split(' ').filter(i => i)

Filter logic also can change in some other cases.


This is a bit old, but for documentation purposes there is also another neat way.

someString.filter(Boolean);

// Example
['fds', '', 'aaaaa', 'AA', 'ffDs', "", 'd'].filter(Boolean);
// Output
["fds", "aaaaa", "AA", "ffDs", "d"]

Edit

How does it work ?

The following are identical

.filter(Boolean)
.filter((value) => Boolean(value))

Boolean() as function behave as a converter of any type to Boolean by the standard input to output.

References:
Global Objects -> Boolean
Truthy
Falsy