check string matches from the given array of string in javascrpit

前端 未结 3 1657
星月不相逢
星月不相逢 2021-01-27 05:05

i trying to match my string with given array of string but this below code is not working,is any suggestion might be help , below code is what i have tried

le         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 05:33

    You can use .some to iterate over the matcherArray with an includes test:

    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');
    }

    Another option would be to turn the matcherArray into a regular expression, with each item separated by | (alternation):

    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');
    }

    Note that the escape function is there so as to escape characters with a special meaning inside a regular expression, such as . (matches any character by default, which isn't what you want here).

提交回复
热议问题