0

I am trying to use jQuery to determine whether a URL contains any of a number of different strings. I have been successful in writing some code to determine if a URL contains just ONE string (see below), but I am not sure how to check if a URL contains any of a host of different possible strings. Logically speaking, I want to use jQuery to determine if a URL contains 'string A' OR 'string B' OR 'string C', etc. I could obviously write a completely different function for each string, but this seems terribly inefficient. Thanks in advance for your input.

$(document).ready(function(){
if(window.location.href.indexOf("360007912231") > -1) {
$("#catchildren1").show();
}
});
Marconi
  • 33
  • 1
  • 7
  • Does this answer your question? [How to check if a string contains text from an array of substrings in JavaScript?](https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript) – Shivashriganesh Mahato Apr 16 '20 at 20:22
  • It may, although i am not seeing how to use that info to resolve the issue I am having. I would think there is a fairly straight forward way to just concatenate 3 or 4 different string values in a function and have jQuery check to see if any of those values are present in a URL. Why can't I simply use the 'OR' operator in the IF statement in my original code sample to specify a second and third value? I did try this, of course, but have not had any success as of yet. – Marconi Apr 16 '20 at 21:44

1 Answers1

0

If I'm understanding your question correctly, you want to check if at least one element in a list of substrings is contained in a string (since window.location.href does return a string). In that case you could just write several "or" clauses in your if statement but that doesn't generalize to an arbitrary list and is a pain to write out if you have a lot to test. That's why I referred you to a regex solution which can be applied to an arbitrary list of substrings. Here's how you could implement it in your code:

let substrings = ["360007912231", ...];

if (new RegExp(substrings.join("|")).test(window.location.href)) {
    $("#catchildren1").show();
}
  • Thank you Shivashriganesh. I have not tried this yet, but it sounds like a reasonable approach and I will give it a whirl (unless the alternate approach I am currently working on provides a solution.). Either way -- it is good to know about this technique. – Marconi Apr 19 '20 at 19:18