lodash 中是否有一种方法可以检查字符串是否包含数组中的值之一?
例如:
var text = 'this is some sample text';
var values = ['sample', 'anything'];
_.contains(text, values); // should be true
var values = ['nope', 'no'];
_.contains(text, values); // should be false
最佳答案
使用_.some
和 _.includes
:
var text = 'this is some sample text';
var values = ['sample', 'anything'];
console.log(_.some(values, (el) => _.includes(text, el)));
var values = ['no', 'nope'];
console.log(_.some(values, (el) => _.includes(text, el)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
更现代的方法是使用原生 JS 来实现同样的事情,而不需要外部库。
const text = 'this is some sample text';
const values1 = ['sample', 'anything'];
const values2 = ['no', 'nope'];
function test(text, arr) {
return arr.some(el => {
return text.includes(el);
});
}
console.log(test(text, values1));
console.log(test(text, values2));
关于javascript - lodash _.包含字符串中的多个值之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37023066/