[英]Remove empty or whitespace strings from array - Javascript
I've found this beautiful 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?有没有一个很好的方法来扩展这个方法来删除空格,或者我应该先通过迭代数组来修剪空格?
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']; console.log("Example 1: " + JSON.stringify(arr.filter(function(entry) { return entry.trim() != ''; }))); console.log("Example 2: " + JSON.stringify(arr.filter(function(entry) { return /\\S/.test(entry); }))); var rex = /\\S/; console.log("Example 3: " + JSON.stringify(arr.filter(rex.test.bind(rex))));
...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']; console.log("Example 4: " + JSON.stringify(arr.filter(entry => !entry.trim() == ''))); console.log("Example 5: " + JSON.stringify(arr.filter(entry => /\\S/.test(entry))));
You can take advantage of empty string as falsy value.您可以利用空字符串作为假值。
You can use Array#filter
with String#trim
.您可以将
Array#filter
与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>
Based on this MDN reference :基于此 MDN 参考:
\\s
Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces.匹配单个空白字符,包括空格、制表符、换页符、换行符和其他 Unicode 空格。 Equivalent to
[ \\f\\n\\r\\t\\v\ \ \\ -\ \ \ \ \ \ \]
.相当于
[ \\f\\n\\r\\t\\v\ \ \\ -\ \ \ \ \ \ \]
。
And on ECMA 262 reference , saying \\s
should match "White Space" like \
(Tab, <TAB>
), \
(Vertical Tab, <VT>
), \
(Form Feed, <FF>
), \
(Space, <SP>
), \
(No-break space, <NBSP>
), \
(Byte Order Mark, <BOM>
), and other category “Zs” ( <USP>
), and also "line terminators" like \
(Line Feed, <LF>
), \
(Carriage Return, <CR>
), \
(Line separator, <LS>
) and \
(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
应该匹配“空白”,如\
(Tab, <TAB>
), \
(Vertical Tab, <VT>
), \
(Form Feed, <FF>
), \
(Space, <SP>
), \
(No-break space, <NBSP>
), \
(Byte Order Mark, <BOM>
),和其他类别“Zs”( <USP>
),还有“行终止符"像\
( \
行, <LF>
), \
(回车, <CR>
), \
(行分隔符, <LS>
)和\
(段落分隔符, <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\ \ \\ -\ \
\
\ \ \ \]
character class:如果某些旧浏览器对
\\s
行为有所不同,请将其替换为[ \\f\\n\\r\\t\\v\ \ \\ -\ \
\
\ \ \ \]
字符类:
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 空间。
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>
const fruits = ['Apple', undefined, ' ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
const Fruits = ['苹果', 未定义, ' ', '芒果', '', '香蕉', ' ', '草莓'];
fruits.filter(fruit => fruit && fruit.trim())
水果过滤器(水果 => 水果&&fruit.trim())
Output: ["Apple", "Mango", "Banana", "Strawberry"]输出:[“苹果”、“芒果”、“香蕉”、“草莓”]
Filter condition: fruit && fruit.trim()
prefix - will remove all the falsy value
suffix - will trim and then remove all the falsy values
A one-line solution written in ES6 for quick use:一个用 ES6 编写的用于快速使用的单行解决方案:
const filterArray=a=>a.filter(x=>typeof x!=='string'||!!x.trim())
Some advantages of this are that it ignores anything that is not a string.这样做的一些优点是它会忽略任何不是字符串的内容。
Without ES6:没有 ES6:
function filterArray(a) {
return a.filter(function(x) {
return typeof x !== 'string' || !!x.trim()
})
}
Example:例子:
const filterArray=a=>a.filter(x=>typeof x!=='string'||!!x.trim()) console.log(filterArray([1, 2, 4, '', '']))
Or if your browser doesn't support ES6 (which it probably does):或者,如果您的浏览器不支持 ES6(它可能支持):
function filterArray(a) { return a.filter(function(x) { return typeof x !== 'string' || !!x.trim() }) } console.log(filterArray([1, 2, 4, '', '']))
I used filter and checking if element length is not equal to zero.我使用过滤器并检查元素长度是否不等于零。 It worked for me, and this solution is short:
它对我有用,这个解决方案很短:
const arr = ['Apple', '', 'Mango', '', 'Banana', '', 'Strawberry'] const arr2 = arr.filter(item => item.length !== 0) console.log(arr2)
function clearSpace(arr){
for (var key in arr) {
if (arr[key] == "") {
arr.splice(key, 1)
clearSpace(arr)
}
}
}
var arr = ["","a","b","",""]
clearSpace(arr)
console.log(arr)
//I hope this helps you!!
//Vu Tien Luong - 3GTEL
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.