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

4
  • Your goal isn't clear. Do you mean that you want to return the index of the matching element in the array? Commented Feb 3, 2020 at 16:44
  • In the above code I want to search for var str if match this two index of array filter
    – Yusuf HR
    Commented Feb 3, 2020 at 17:01
  • That doesn't really clear it up. It's your misuse of the word 'index' that's confusing matters. What should the response be from the lookup? Commented Feb 3, 2020 at 17:02
  • i mean values instead of 'index'
    – Yusuf HR
    Commented Feb 3, 2020 at 17:05

3 Answers 3

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

2
  • i have edited the question.
    – Yusuf HR
    Commented Feb 3, 2020 at 17:07
  • updated the answer. Commented Feb 3, 2020 at 17:11
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)

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.