Industrial Industrial - 1 year ago 72
Javascript Question

Splitting string by whitespace, without empty elements?

I am trying to explode an string using javascript to pick searchterms, whitespace-separated. However I get empty array elements if a searchterm is ended by a whitespace, as shown below.

What should I do instead to avoid post-processing this array and removing empty elements?

var str = "searchterm1 searchterm2";
console.log(str.split(" ")); // ["searchterm1", "searchterm2"]

var strb = "searchterm1 "; // Note the ending whitespace
console.log(strb.split(" ")); // ["searchterm1", ""]

Answer Source

You could simply match all non-space character sequences:

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