检查javascrpit中给定字符串数组中的字符串是否匹配

时间:2018-11-16 06:22:26

标签: javascript typescript

我试图将我的字符串与给定的字符串数组匹配,但是下面的代码不起作用,是否有任何建议可能是帮助,下面的代码是我尝试过的

let myLongString = 'jkjdssfhhabf.pdf&awersds=oerefsf';
let matcherArray = ['.pdf', '.jpg'];

if (myLongString.match(matcherArray)) {
    return true;
} else {
    return false;
}

预期输出为true。有没有更好的解决方案可以解决这种类型的问题呢?

3 个答案:

答案 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));