Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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", ""]
like image 381
Industrial Avatar asked Feb 04 '12 15:02

Industrial


People also ask

How to split and remove string in javascript?

To split a string and remove the empty elements from the array, call the split() method on the string to get an array of substrings and use the filter() method to filter out any empty elements from the array, e.g. str. split(' '). filter(element => element) . Copied!

Can you split an empty string?

The split() method does not change the value of the original string. If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

How do you split a substring?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.


2 Answers

You could simply match all non-space character sequences:

str.match(/[^ ]+/g)
like image 167
Gumbo Avatar answered Oct 05 '22 07:10

Gumbo


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.

like image 24
user1079877 Avatar answered Oct 05 '22 08:10

user1079877