Skip to main content

How to Split a String and Remove Empty Elements in JavaScript

When you split a string in JavaScript using String.prototype.split(), the resulting array can often contain empty strings. This happens if the delimiter appears at the start or end of the string, or if multiple delimiters are next to each other. These empty strings are usually unwanted and need to be removed.

This guide will teach you the modern and idiomatic way to split a string and immediately filter out any empty elements by chaining the Array.prototype.filter() method.

The Core Problem: split() Creates Empty Strings

The split() method is very literal. It creates an array element for every section between the delimiters, which can result in empty strings.

Example of problem:

// Problem: Multiple spaces and leading/trailing spaces create empty strings.
let messyString = ' apple banana cherry ';

let parts = messyString.split(' ');

console.log(parts);

Output:

[ '', '', 'apple', '', 'banana', 'cherry', '' ] (This is messy!)
note

You almost never want those empty strings in your final array.

The Solution: Chaining split() and filter()

The most readable and modern way to solve this is to immediately chain the filter() method after split(). We can use a concise trick with the Boolean constructor to remove all "falsy" values, including empty strings.

let messyString = '  apple  banana cherry ';

// 1. Split the string into an array, including empty strings.
// 2. Filter out all falsy values from the array.
let cleanArray = messyString.split(' ').filter(Boolean);

console.log(cleanArray);

Output:

['apple', 'banana', 'cherry']
note

This is the recommended best practice for its conciseness and clarity.

How the filter(Boolean) Trick Works

The Array.prototype.filter() method creates a new array containing only the elements for which its callback function returns a "truthy" value.

In JavaScript, certain values are considered "falsy":

  • '' (an empty string)
  • 0
  • false
  • null
  • undefined
  • NaN

All other values are "truthy."

When you pass Boolean as the callback function (.filter(Boolean)), you are essentially doing this:

let parts = ['', 'apple', '', 'banana'];

let result = parts.filter(item => {
return Boolean(item); // Boolean('') is false, Boolean('apple') is true
});

console.log(result);

Output:

['apple', 'banana']
note

The filter(Boolean) syntax is a widely-used and idiomatic shortcut for this exact operation.

An Alternative for Splitting by Spaces: match()

If your specific goal is to split a string by any whitespace (one or more spaces, tabs, or newlines) and get an array of the "words," using String.prototype.match() with a regular expression can be a more direct approach.

let messyString = '  apple \n banana\tcherry ';

// The regex /\S+/g matches any sequence of one or more non-whitespace characters.
let words = messyString.match(/\S+/g) || [];

console.log(words);

Output:

['apple', 'banana', 'cherry']
note

This method avoids creating the intermediate array with empty strings altogether. However, for splitting by a specific, non-space delimiter (like a comma), the split().filter() pattern is generally more applicable.

Conclusion

Cleaning up the result of a split() operation is a simple task with modern functional array methods.

  • The recommended best practice is to chain filter() after split() to remove unwanted empty strings: string.split(separator).filter(Boolean).
  • This filter(Boolean) trick is an idiomatic and concise way to remove all "falsy" values from an array.
  • For the specific case of splitting by whitespace, using string.match(/\S+/g) can be a more direct alternative.