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
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
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"]
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.
You could simply match all non-space character sequences:
str.match(/[^ ]+/g)
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"]