从数组中删除空字符串或空格字符串 - Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35476948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove empty or whitespace strings from array - Javascript
提问by Daniel
I've found thisbeautiful method for removing empty strings - arr = arr.filter(Boolean)
.
我发现了这个删除空字符串的漂亮方法 - arr = arr.filter(Boolean)
。
But it doesn't seem to work on whitespace strings.
但它似乎不适用于空白字符串。
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
arr = arr.filter(Boolean);
// ["Apple", " ", "Mango", "Banana", " ", "Strawberry"]
// should be ["Apple", "Mango", "Banana", "Strawberry"]
Is there a nice way to expand this method to removing whitespaces as well or should i trim the whitespaces by iterating the array first?
有没有一个很好的方法来扩展这个方法来删除空格,或者我应该先通过迭代数组来修剪空格?
回答by T.J. Crowder
filter
works, but you need the right predicate function, which Boolean
isn't (for this purpose):
filter
有效,但您需要正确的谓词函数,这Boolean
不是(为此目的):
// 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#trim
arr = 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.)
(\S
意思是“一个非空白字符”,所以/\S/.test(...)
检查一个字符串是否至少包含一个非空白字符。)
or (perhaps a bit overboard and harder to read)
或(可能有点过火且难以阅读)
// Example 3
var rex = /\S/;
arr = arr.filter(rex.test.bind(rex));
With an ES2015 (aka ES6) arrow function, that's even more concise:
使用 ES2015(又名 ES6)箭头函数,更简洁:
// Example 4
arr = arr.filter(entry => entry.trim() != '');
or
或者
// Example 5
arr = arr.filter(entry => /\S/.test(entry));
Live Examples-- The ES5 and earlier ones:
实时示例——ES5 及更早的示例:
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
snippet.log("Example 1: " + JSON.stringify(arr.filter(function(entry) { return entry.trim() != ''; })));
snippet.log("Example 2: " + JSON.stringify(arr.filter(function(entry) { return /\S/.test(entry); })));
var rex = /\S/;
snippet.log("Example 3: " + JSON.stringify(arr.filter(rex.test.bind(rex))));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
...and the ES2015 (ES6) ones (won't work if your browser doesn't support arrow functions yet):
...以及 ES2015 (ES6) 的(如果您的浏览器尚不支持箭头功能,则无法使用):
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
snippet.log("Example 4: " + JSON.stringify(arr.filter(entry => !entry.trim() == '')));
snippet.log("Example 5: " + JSON.stringify(arr.filter(entry => /\S/.test(entry))));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
回答by Tushar
You can take advantage of empty string as falsy value.
您可以利用空字符串作为假值。
You can use Array#filter
with String#trim
.
Using ES6 Arrow function:
使用 ES6 箭头功能:
arr = arr.filter(e => String(e).trim());
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
var nonEmpty = arr.filter(e => String(e).trim());
document.getElementById('result').innerHTML = JSON.stringify(nonEmpty, 0, 4);
<pre id="result"></pre>
Using ES5 anonymous function:
使用 ES5 匿名函数:
arr = arr.filter(function(e) {
return String(e).trim();
});
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
var nonEmpty = arr.filter(function(e) {
return String(e).trim();
});
document.getElementById('result').innerHTML = JSON.stringify(nonEmpty, 0, 4);
<pre id="result"></pre>
回答by Wiktor Stribi?ew
Based on this MDN reference:
基于此 MDN 参考:
\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]
.
\s
匹配单个空白字符,包括空格、制表符、换页符、换行符和其他 Unicode 空格。相当于[ \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:
在ECMA 262 参考中,说\s
应该匹配“空白”,如\u0009
(Tab, <TAB>
), \u000B
(Vertical Tab, <VT>
), \u000C
(Form Feed, <FF>
), \u0020
(Space, <SP>
), \u00A0
(No-break space, <NBSP>
), \uFEFF
(Byte Order Mark, <BOM>
) , 和其他类别“Zs” ( <USP>
),以及“行终止符”,如\u000A
(Line Feed, <LF>
), \u000D
(Carriage Return, <CR>
), \u2028
(Line separator, <LS>
) 和\u2029
(Paragraph separator, <PS>
),您可以使用以下代码删除元素仅当trim()
本机不可用时才为空或空白:
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:
如果某些旧浏览器的行为与 不同\s
,请将其替换为[ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?-\u200a?\u2028\u2029\u202f\u205f?\u3000\ufeff]
字符类:
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.
您还可以进一步自定义它以包含新的 Unicode 空间。
回答by Atit More
You Can try this approach. I found this process simple and it work for me.
你可以试试这个方法。我发现这个过程很简单,而且对我有用。
let arrayEle = ["abc", " "," ", "def", "xyz", " "];
arrayEle = arrayEle.filter((element) => {
return /\S/.test(element);
});
console.log(arrayEle);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
回答by guest271314
Could use Array.protype.join()
, String.prototype.split()
with parameter RegExp
/\s|,/
followed by .filter(Boolean)
可以使用Array.protype.join()
,后跟String.prototype.split()
参数RegExp
/\s|,/
.filter(Boolean)
var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
arr = arr.join().split(/\s|,/).filter(Boolean);
console.log(arr)