Based on this MDN reference:
\s
Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
.
And on ECMA 262 reference, saying \s
should match "White Space" like \u0009
(Tab, <TAB>
), \u000B
(Vertical Tab, <VT>
), \u000C
(Form Feed, <FF>
), \u0020
(Space, <SP>
), \u00A0
(No-break space, <NBSP>
), \uFEFF
(Byte Order Mark, <BOM>
), and other category “Zs” (<USP>
), and also "line terminators" like \u000A
(Line Feed, <LF>
), \u000D
(Carriage Return, <CR>
), \u2028
(Line separator, <LS>
) and \u2029
(Paragraph separator, <PS>
), you can use the following code to remove elements that are either empty or whitespace only if trim()
is not natively available:
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
arr = arr.filter(s => s.replace(/\s+/g, '').length !== 0);
// Or for ES5
// arr = arr.filter(function (el) { return el.replace(/\s+/g, '').length !== 0; });
console.log(arr);
In case some old browsers behave differently with \s
, replace it with [ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
character class:
arr = arr.filter(function (el) { return el.replace(/[ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/g, '').length !== 0; });
And you can also customize it further to include new Unicode spaces to come.