Split a String removing any Empty Elements in JavaScript

avatar

Borislav Hadzhiev

Tue Nov 16 20212 min read

banner

Photo by Chi Lok Tsang

Split a String removing any Empty Elements #

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).

index.js
const str = ' apple banana kiwi '; const result = str.split(' ').filter(element => element); console.log(result); // ๐Ÿ‘‰๏ธ ['apple', 'banana' , 'kiwi']

The only parameter we passed to the String.split method is the separator, on which we want to split the string.

The method returns an array of substrings.

index.js
const str = ' apple banana kiwi '; // ๐Ÿ‘‡๏ธ ['', 'apple', 'banana', 'kiwi', ''] console.log(str.split(' '));

The function we passed to the Array.filter method gets called with each element in the array.

On each iteration, we return the string as is.

This works, because the filter method returns a new array containing only the truthy elements that the callback function returned.

Truthy are all values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

Since empty strings are falsy values, they don't get added to the new array.

Because we're splitting a string to an array, we know that the array will only contain strings and the only string that's a falsy value is an empty string.

This means that there isn't any edge we need to handle, e.g. the array containing other falsy values, like 0.

An alternative approach is to pass the Boolean object to the filter method.

To split a string and remove any empty elements from the array:

  1. Call the split() method on the string to get an array of substrings.
  2. Call the filter() method on the array.
  3. Pass the Boolean object as a parameter to the filter method.
index.js
const str = ' apple banana kiwi '; const result = str.split(' ').filter(Boolean); console.log(result); // ๐Ÿ‘‰๏ธ ['apple', 'banana' , 'kiwi']

The Boolean object takes a value as a parameter and converts the value to its boolean representation.

index.js
console.log(Boolean('hello')); // ๐Ÿ‘‰๏ธ true console.log(Boolean(' ')); // ๐Ÿ‘‰๏ธ true console.log(Boolean('')); // ๐Ÿ‘‰๏ธ false

On each iteration, the string gets passed to the Boolean object, gets converted to its boolean representation and gets returned.

Any of the empty strings evaluate to false, which is a falsy value and doesn't get added to the new array.

Which approach you pick is a matter of personal preference. I'd go with the first approach, because I find it more direct and intuitive.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee