admin管理员组文章数量:1246503
Is there a lodash function that takes an array of needles, and searches a string (haystack) for at least one match? For example:
let needles = ['one', 'two', 'three']
let str = 'one in every thousand will quit their jobs'
I need to search str
to see if it contains at least one of the needles
. I can implement this without lodash, but if there's a function that will help out I'd rather not reinvent the wheel as I already have lodash loaded into my project.
Is there a lodash function that takes an array of needles, and searches a string (haystack) for at least one match? For example:
let needles = ['one', 'two', 'three']
let str = 'one in every thousand will quit their jobs'
I need to search str
to see if it contains at least one of the needles
. I can implement this without lodash, but if there's a function that will help out I'd rather not reinvent the wheel as I already have lodash loaded into my project.
4 Answers
Reset to default 7Use
Array#some
, Thesome()
method tests whether some element in the array passes the test implemented by the provided function.
let needles = ['one', 'two', 'three']
let str = 'one in every thousand will quit their jobs';
let bool = needles.some(function(el) {
return str.indexOf(el) > -1;
});
console.log(bool);
You can use Array.protype.some()
and String.prototype.includes()
:
needles.some(function(needle) {
return str.includes(needle);
});
Or their lodash's equivalents:
_.some(needles, function(needle) {
return _.includes(str, needle);
});
Use _.some()
to iterate the needles, testing if it can be found in the string.
let found = _.some(needles, function(needle) {
return str.indexOf(needle) != -1;
});
However, if there are lots of needles, it may be more efficient to convert it to a regular expression.
let needleRE = new RegExp(needles.map(_.escapeRegExp).join('|'));
let found = needleRE.test(str);
let needles = ['one', 'two', 'three']
let str = 'one in every thousand will quit their jobs'
let joinedNeedles = needles.join("|");
let regex = new RegExp(joinedNeedles)
let matches = str.match(regex) // ['one']
matches will return an array of matched ones.
本文标签: javascriptLodash Search a string for at least 1 value in an arrayStack Overflow
版权声明:本文标题:javascript - Lodash: Search a string for at least 1 value in an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740255325a2249258.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论