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", ""]
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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With