Remove empty or whitespace strings from array - Javascript Remove empty or whitespace strings from array - Javascript arrays arrays

Remove empty or whitespace strings from array - Javascript


filter works, but you need the right predicate function, which Boolean isn't (for this purpose):

// Example 1 - Using String#trim (added in ES2015, needs polyfilling in outdated// environments like IE)arr = arr.filter(function(entry) { return entry.trim() != ''; });

or

// Example 2 - Using a regular expression instead of String#trimarr = arr.filter(function(entry) { return /\S/.test(entry); });

(\S means "a non-whitespace character," so /\S/.test(...) checks if a string contains at least one non-whitespace char.)

or (perhaps a bit overboard and harder to read)

// Example 3var rex = /\S/;arr = arr.filter(rex.test.bind(rex));

With an ES2015 (aka ES6) arrow function, that's even more concise:

// Example 4arr = arr.filter(entry => entry.trim() != '');

or

// Example 5arr = arr.filter(entry => /\S/.test(entry));

Live Examples -- The ES5 and earlier ones: