Search in a Jquery object for multiple strings stored in an array

239 views Asked by At

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.

2

There are 2 answers

3
Adrian On

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

1
Jonas Wilms On
 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)