0

How can I find a match in an array of strings using Javascript? For example:

var str = "https://exmaple.com/u/xxxx?xx=x";
var filter = ["/u","/p"];
if (!str.includes(filter)){
  return 1;
}

In the above code I want to search for var str if match this two values of array filter

Yusuf HR
  • 92
  • 2
  • 10

3 Answers3

2

This should work:

var str = "https://exmaple.com/u/xxxx?xx=x";
var filters = ["/u","/p"];

for (const filter of filters) {
  if (str.includes(filter)) {
    console.log('matching filter:', filter);
    break; // return 1; if needed
  }
}
technophyle
  • 7,972
  • 6
  • 29
  • 50
0

In your array you need to find the element which includes "/u". filter will return an array and will contain only those element which includes u

var x = ["https://exmaple.com/u/xxxx?xx=x", "https://exmaple.com/p/xxxx?xx=x"];
let matched = x.filter(item => item.includes("/u"));

console.log(matched)
brk
  • 48,835
  • 10
  • 56
  • 78
0

Try this:

var x = ["https://exmaple.com/u/xxxx?xx=x","https://exmaple.com/p/xxxx?xx=x"], i;

for (i = 0; i < x.length; i++) {
  if(x[i].includes('/u')) {
    document.write(x[i]);
  }
}

This loops through all the URLs and picks the one that has /u in it. Then it just prints that out.

Angshu31
  • 1,172
  • 1
  • 8
  • 19