I have a line of legacy code to split a string on semi-colons:
var adds = emailString.split(/;+/).filter(Boolean);
What could the filter(Boolean)
part do?
I have a line of legacy code to split a string on semi-colons:
var adds = emailString.split(/;+/).filter(Boolean);
What could the filter(Boolean)
part do?
-
Can you also add
emailString
value – Tushar Commented Nov 4, 2015 at 8:04 - 1 I don't understand how this question got two cowardly downvotes, yet the answer it evoked has two upvotes. – ProfK Commented Nov 9, 2015 at 6:28
1 Answer
Reset to default 8filter(Boolean)
will only keep the truthy values in the array.
filter
expects a callback function, by providing Boolean
as reference, it'll be called as Boolean(e)
for each element e
in the array and the result of the operation will be returned to filter
.
If the returned value is true
the element e
will be kept in array, otherwise it is not included in the array.
Example
var arr = [0, 'A', true, false, 'tushar', '', undefined, null, 'Say My Name'];
arr = arr.filter(Boolean);
console.log(arr); // ["A", true, "tushar", "Say My Name"]
In the code
var adds = emailString.split(/;+/).filter(Boolean);
My guess is that the string emailString
contains values separated by ;
where semicolon can appear multiple times.
> str = '[email protected];;;;[email protected];;;;[email protected];'
> str.split(/;+/)
< ["[email protected]", "[email protected]", "[email protected]", ""]
> str.split(/;+/).filter(Boolean)
< ["[email protected]", "[email protected]", "[email protected]"]
Here split
on this will return ["[email protected]", "[email protected]", "[email protected]", ""]
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745398223a4625978.html
评论列表(0条)