最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the `filter` call for in this string split operation? - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked Nov 4, 2015 at 8:01 ProfKProfK 51.2k126 gold badges417 silver badges801 bronze badges 2
  • 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
Add a ment  | 

1 Answer 1

Reset to default 8

filter(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]", ""].

发布评论

评论列表(0)

  1. 暂无评论