Using a variable for if window.location.href.indexOf ()

What I want to do is use a variable with window.location.href.indexOf () This is my code right now, I want to shorten it.

var urls  = [
'https://www.example.com/' 
,'https://www.example2.com/' 
,'https://www.example3.com/'  
,'https://www.example4.com/'
,'https://www.example5.com/'
];



// if ((window.location.href.indexOf(""+urls+"") > -1) Does not work
if (
(window.location.href.indexOf("https://www.example.com/") > -1)
|| (window.location.href.indexOf("https://www.example2.com/") > -1)
|| (window.location.href.indexOf("https://www.example3.com/") > -1)
|| (window.location.href.indexOf("https://www.example4.com/") > -1)
|| (window.location.href.indexOf("https://www.example5.com/") > -1)   
) {
//do stuff

}

I included what I tried in the code, but it does not work. javascript and jquery work for me

+4
source share
5 answers

Check how it is

if (urls.indexOf(window.location.href) > -1)
+3
source

You need to use the indexOfarray to search window.location.hrefinside the array of URLs.

Edit

if ((window.location.href.indexOf(""+urls+"") > -1)

For

if (urls.indexOf(window.location.href) > -1)
+3
source

:

if (urls.indexOf(window.location.href) > -1)

if ((window.location.href.indexOf(""+urls+"") > -1)
+3
var href = window.location.href; 

//there you need to strip params and leave only domain (https://www.example.com/index.php?q=a convert to https://www.example.com/)

//and then
if (urls.indexOf(href) > -1) {...}
+2

URL- , URL- :

var test = false;
for(var i=0; i < urls.length; i++) {
    test = test || location.href.indexOf(urls[i]) > -1;
}

if( test ) {
    //do stuff
}
0

All Articles