0

I'm not entirely sure if the title of my question makes any sense but I'll try and explain it further as I'm struggling to get this code working.

I'm scanning through a page for any script tags and I then extract the src values of them. All I want to do now is to check if the Jquery object has either of the two specific directories within it. If it does then I will do some other work with them. My code so far looks like this;

var scriptTags = $('script');
var directoryNames = ['abc/custom','xyz/custom'];

for (var i = 0; i < scriptTags.length; i++) {
    var srcVal = scriptTags[i].src;
    if (ANY DIRECTORY NAME VALUES FOUND WITHIN scriptTags) {
        console.log('found');
    }

}

I'd really appreciate if anyone could shed some light on this,please?

Thanks.

Jayonline
  • 143
  • 11
  • Possible duplicate of [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) – Heretic Monkey Jun 26 '18 at 15:13
  • Please check the pen for an example. https://codepen.io/anon/pen/RJYYoZ?editors=0011 – Jayonline Jun 26 '18 at 15:44

2 Answers2

0

You're looking for directoryNames.indexOf(srcVal).

The indexOf function will return the index in the array of the element that was found (srcVal) and if it's not found it'll return -1.

End product:

if(directoryNames.indexOf(srcVal) > -1) ...

Adrian
  • 8,271
  • 2
  • 26
  • 43
-2
 if(directoryNames.some(name => srcVal.includes(name)))

Just go over all directory names and check if they are part of the current url. Or if you got a lot of urls it might be better to build a tree of directories:

const root = {};
for(const url of directoryNames) {
  let acc = root;
   for(const path of url.split("/")) {
     acc = acc[path] = acc[patch] || {};
   }
   acc.isEnd= true;
}

So then you can check an url with:

if(srcVal.split("/").reduce((acc, path) => acc[path] || {}, root).isEnd)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151