非常直截了当。在javascript中,我需要检查字符串是否包含数组中持有的任何子字符串。
当前回答
最好的答案是: 这也是不区分大小写的
var specsFilter = [.....];
var yourString = "......";
//if found a match
if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
// do something
}
其他回答
以下是目前为止(在我看来)最好的解决方案。这是一个现代的(ES6)解决方案,它:
是高效的(一行!) 避免for循环 与其他答案中使用的some()函数不同,这个函数不仅返回一个布尔值(true/false) 相反,它要么返回子字符串(如果它在数组中找到),要么返回undefined 更进一步,允许您选择是否需要部分子字符串匹配(示例如下)
享受吧!
const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));
在这里,found将被设置为'abc'。这将适用于精确的字符串匹配。
如果你用:
const found = arrayOfStrings.find(v => str.includes(v));
同样,found在本例中被设置为'abc'。这不允许部分匹配,所以如果str被设置为'ab', found将是未定义的。
And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));
代替。如果str被设为'ab' found就会被设为'abc'
容易peasy !
基于t。j。克劳德的答案
使用转义的RegExp测试至少一个子字符串的“至少一次”出现。
函数buildSearch(substrings) { 返回新的RegExp( 子字符串 . map(函数(s) {s.replace返回 (/[.*+?^${}()|[\]\\]/ g , '\\$&');}) .join('{1,}|') + '{1,}' ); } var pattern = buildSearch(['hello','world']); console.log(模式。测试('你好')); console.log(模式。Test ('what a wonderful world')); console.log(模式。Test ('my name is…'));
Javascript函数使用搜索字符串或搜索字符串数组搜索标签或关键字数组。(使用ES5的一些数组方法和ES6的箭头函数)
// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
// array matches
if (Array.isArray(b)) {
return b.some(x => a.indexOf(x) > -1);
}
// string match
return a.indexOf(b) > -1;
}
使用示例:
var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
// 1 or more matches found
}
最好的答案是: 这也是不区分大小写的
var specsFilter = [.....];
var yourString = "......";
//if found a match
if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
// do something
}
我也遇到过这样的问题。我有一个URL,我想检查链接是否以图像格式或其他文件格式结束,有一个图像格式数组。以下是我所做的:
const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
// false
推荐文章
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 不区分大小写的列表排序,没有降低结果?
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- 如何在Java中将int[]转换为Integer[] ?
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组