I need to be able to check a URL to see if it contains a second level domain (SLD) for a valid streaming service. Note, the "hulu" in www.hulu.com is what I mean by an SLD.
Rather than parsing the URL with regex to get just the SLD, or using something like location.hostname.split('.').pop()
to get the SLD, I thought I could use indexOf instead. And this works great (for me at least, I realize it's got at least one serious limitation - see my note below).
Example. Let's say I want to see if https://www.hulu.com/watch/...
is an Hulu link. This works:
let string = 'https://www.hulu.com/watch/...';
string.indexOf('hulu') > -1 ? true : false; // returns true
What I want to be able to do is pass an array of possible strings into indexOf. Something like this:
let validSLDs = ['hulu','netflix']
let string1 = 'www.hulu.com/watch/...';
let string2 = 'http://www.netflix.com/watch/...';
let string3 = 'imdb.com/title/....'
string1.indexOf(validSLDs); // returns true ('hulu' is a valid SLD)
string2.indexOf(validSLDs); // returns true ('netflix' is a valid SLD)
string3.indexOf(validSLDs); // returns false ('imdb' is not a valid SLD)
But of course this doesn't work because indexOf()
is expecting to be passed a string, not an array of strings.
So is there some similarly easy, elegant (vanilla JS) solution that I'm not thinking of?
The next easiest thing I could think of would be to loop through my array of validSLDs and call indexOf on each of the SLDs. And maybe that is the best approach. I just thought I'd see if anyone else had a better solution. Thanks in advance!
NOTE: I realize that my entire approach is a lazy approach and could result in possible issues. For example, https://www.amazon.com/how-cancel-hulu-subscription-membership/...
would also return true using the code above, because the word "hulu" exists in the string ... but isn't an SLD. I'm ok with that because we have some control over the URL's we need to validate.