Split a String removing any Empty Elements in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
4 min

banner

# Split a String removing any Empty Elements in JavaScript

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

  1. Use the split() method to get an array of substrings.
  2. Use the filter() method to remove the empty elements from the array.
  3. The filter method will return a new array without empty elements.
index.js
const str = ' bobby hadz com '; const arr = str.split(' ').filter(element => element); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

split string removing any empty elements

The code for this article is available on GitHub

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

The method returns an array of substrings.

index.js
const str = ' bobby hadz com '; // ๐Ÿ‘‡๏ธ [ '', 'bobby', '', '', 'hadz', 'com', '' ] 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.

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

All other values are truthy.

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

We are splitting a string into an array, so we know that the array will only contain strings.

Only empty strings are falsy values.

So 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() constructor to the filter() method.

# Split a String removing any Empty Elements using Boolean()

This is a three-step process:

  1. Use the split() method to split the string into an array.
  2. Call the filter() method on the array.
  3. Pass the Boolean() constructor as a parameter to the filter() method.
index.js
const str = ' bobby hadz com '; const arr = str.split(' ').filter(Boolean); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

split string removing any empty elements using boolean

The code for this article is available on GitHub

The Boolean() constructor 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() constructor, then gets converted to its boolean representation and gets returned.

All of the empty strings evaluate to false and don't get added to the new array.

# Split a String removing any Empty Elements using match

If you're splitting on a space, you can also use the String.match() method.

index.js
const str = ' bobby hadz com '; const arr = str.match(/\S+/g) console.log(arr) // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

split string removing any empty elements using match

The code for this article is available on GitHub

The String.match() method matches a string against a regular expression.

The method returns an array containing the matches (if any) or null if no matches are found.

We passed a regular expression to the match method.

The forward slashes / / mark the beginning and end of the regex.

The \S character matches any single character other than white space.

The plus + matches the preceding item (any non-whitespace character) 1 or more times.

We used the g (global) flag because we want to match all occurrences of non-whitespace characters and not just the first occurrence.

In its entirety, the regular expression matches one or more non-whitespace characters.

The same approach can be used to split on other characters and remove the empty elements.

index.js
const str = ',bobby,hadz,com,'; const arr = str.match(/[^,]+/g) console.log(arr) // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

The code sample splits by a comma.

The square brackets in the regex are called a character class [].

The caret ^ symbol means "NOT the following".

The regex matches one or more consecutive characters that are not a comma.

No empty elements are contained in the array because the commas don't get matched at all.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev