This post will discuss how to remove empty strings from an array in JavaScript.

There are several ways to remove empty strings from an array in JavaScript. Here are some examples of how to remove empty strings from an array in JavaScript given an array:

1. Using filter() function

The filter() function allows us to create a new array with all elements that pass a test implemented by a provided function. We can use it to filter out the empty strings from the original array by returning true for all elements that are not empty. For example, if we have an array and we want to remove the empty strings, we can do:

Download  Run Code

 
We can use the arrow function (=>) as the callback for the filter() function. This is a new feature of JavaScript that allow writing concise functions with a shorter syntax. For example,

Download  Run Code

 
We can use the trim() function to filter out strings that contain only whitespace characters, such as spaces, tabs, or newlines. The trim() function removes any leading and trailing whitespace characters from a string. For example, the callback function now returns true for every element in the array that is not an empty string after trimming.

Download  Run Code

2. Using length property

The length property returns the number of characters in a string. To use it, we need to pass a function that returns true for every element in the array that has a length greater than zero. This will filter out empty strings, since they have a length of zero. For instance:

Download  Run Code

3. Using a regular expression

This is another technique that works in any version of JavaScript. It involves using a regular expression to match and replace all the empty strings in the original array with an empty value. For example, if we have an array and we want to remove the empty strings, we can join the array with commas, replace all double commas with single commas, and split the string back into an array:

Download  Run Code

That’s all about removing empty strings from an array in JavaScript.