check string matches from the given array of string in javascrpit

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

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

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

expected output is true. is there is any better solution is there to solve this type question thank you.

Answers:

Answer

No need to loop

let myLongString = 'jkjdssfhhabf.pdf&awersds=oerefsf';
console.log(/\.(jpe?g|pdf)/i.test(myLongString));

Answer
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
}

The indexOf() method searches the your array for the specified item, and returns its position.

Answer

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).

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.