Reputation: 42758
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", ""]
Upvotes: 69
Views: 60510
Reputation: 53159
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 '));
Upvotes: 3
Reputation: 12196
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
Upvotes: 26
Reputation: 3574
If you want a function that you can use, just extend String:
String.prototype.splitNoSpaces = function(){
return this.split(' ').filter(function(i){return i});
};
//Now use it!
var classString = "class1 class2 class3 class4";
var classArray = classString.splitNoSpaces();
//classArray[0] is class1
//classArray[1] is class2
//classArray[2] is class3
//classArray[3] is class4
Thanks to @user1079877 for the hint
Upvotes: 1
Reputation: 9368
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.
Upvotes: 72
Reputation: 836
Add function:
//Some browsers support trim so we check for that first
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
Then call trim on the string:
var strb = "searchterm1 "; // Note the ending whitespace
console.log(strb.trim().split(" ")); // ["searchterm1"]
Upvotes: 0
Reputation: 655239
You could simply match all non-space character sequences:
str.match(/[^ ]+/g)
Upvotes: 81