4

What I want to do is use a variable with window.location.href.indexOf() This is my code right now, I want to be able 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've included what I've tried in the code but it doesn not work. javascript and jquery both work for me

5 Answers5

3

You need to use indexOf on array to search the window.location.href within array of urls.

Change

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

To

if (urls.indexOf(window.location.href) > -1)
Adil
  • 143,427
  • 25
  • 201
  • 198
3

Try like this:

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

instead of

if ((window.location.href.indexOf(""+urls+"") > -1)
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319
3

Check like this

if (urls.indexOf(window.location.href) > -1)
Sudharsan S
  • 15,058
  • 3
  • 28
  • 49
2
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) {...}
Arūnas Smaliukas
  • 3,129
  • 6
  • 25
  • 45
0

Since you already have the URLs in an array, you can use a loop to test the URLs as follows:

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

if( test ) {
    //do stuff
}
PeterKA
  • 22,910
  • 4
  • 23
  • 48