我试图将我的字符串与给定的字符串数组匹配,但是下面的代码不起作用,是否有任何建议可能是帮助,下面的代码是我尝试过的
let myLongString = 'jkjdssfhhabf.pdf&awersds=oerefsf';
let matcherArray = ['.pdf', '.jpg'];
if (myLongString.match(matcherArray)) {
return true;
} else {
return false;
}
预期输出为true
。有没有更好的解决方案可以解决这种类型的问题呢?
答案 0 :(得分:3)
var Arrayvalue = ["a","b","c"];
var matchstring = "v";
if (Arrayvalue .indexOf(matchstring) > -1) {
// if it is matches the array it comes to this condition
} else {
// if it is matches the array it comes to this condition
}
indexOf()方法在您的数组中搜索指定的项目,并返回其位置。
答案 1 :(得分:2)
您可以使用.some
通过matcherArray
测试遍历includes
:
let myLongString = 'jkjdssfhhabf.pdf&awersds=oerefsf';
let matcherArray = ['.pdf', '.jpg'];
if (matcherArray.some(str => myLongString.includes(str))) {
console.log('match');
} else {
console.log('no match');
}
另一种选择是将matcherArray
转换为正则表达式,每一项之间用|
(替代)分隔:
const myLongString = 'jkjdssfhhabf.pdf&awersds=oerefsf';
const matcherArray = ['.pdf', '.jpg'];
const escape = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(
matcherArray
.map(escape)
.join('|')
);
if (re.test(myLongString)) {
console.log('match');
} else {
console.log('no match');
}
请注意,escape
函数用于在正则表达式内转义具有特殊含义的字符,例如.
(与任何字符< / em>,这不是您想要的)。
答案 2 :(得分:1)
无需循环
let myLongString = 'jkjdssfhhabf.pdf&awersds=oerefsf';
console.log(/\.(jpe?g|pdf)/i.test(myLongString));