Split a String removing any Empty Elements in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 27, 2022

banner

Photo from Unsplash

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

We're splitting a string to an array, so 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 case 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 and converts it 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 and don'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 explicit.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.