Skip to content
Advertisement

Check if url contains blacklisted strings javascript

If i have an array of blacklisted words like so:

banLinks = ["hello.com","test.net","this.com"];

and I’d like to check if myLink I got through a.getAttribute("href") contains one of those words what’d be the best way to go? Right now i’m trying this but it doesn’t work:

            for (let i = 0; i < banLinks.length; ++i) {
                if ( myLink.indexOf(banLinks[i]) <= -1 ){
                    urllink = myLink;
                }
            }

full section:

    var urllink;
    const banLinks = ["hello.com","test.net","this.com"];
    for (let j = 0; j < titlesArray.length; ++j) {
        if ( "some logic not important" ){

            for (let i = 0; i < banLinks.length; ++i) {
                if ( titlesArray[j].link.indexOf(banLinks[i]) <= -1 ){
                    urllink = titlesArray[j].link;
                }
            }

        }
    };

Advertisement

Answer

Are you in a situation where you’re unable to use Array.prototype.findIndex? (I.e. you must support IE)

If not:

const banLinks = ["hello.com","test.net","this.com"];
const is_banned = banLinks.findIndex(bl => myLink.indexOf(bl) > -1) > -1

And with your edited example:

const banLinks = ["hello.com","test.net","this.com"];
// is_banned is now a function that ingests a link.
const is_banned = (myLink) => banLinks.findIndex(bl => myLink.indexOf(bl) > -1) > -1
// Get first link from titlesArray that is not banned.
const urllink = titlesArray.map(t => t.link).find(li => is_banned(li) == false)

Though this is all guessing based on the code you’ve provided. It’s not very clear what you’re attempting to do in your for loop. If it’s to find the first valid (i.e., NOT banned) urllink, you should break after you’ve found it. Otherwise, subsequent valid urllinks from the rest of titlesArray will override the earlier ones.

Advertisement