28

I am using this code to detect the homepage and it works great:

var url= window.location.href;
if(url.split("/").length>3){
    alert('You are in the homepage');
}

My problem is that I also need to detect if the url has variables for example:

mysite.com?variable=something

I need to also detect if the url has variables on it too

How can I do this?

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
Satch3000
  • 47,356
  • 86
  • 216
  • 346

6 Answers6

81

Using window.location.pathname could work too:

if ( window.location.pathname == '/' ){
    // Index (home) page

} else {
    // Other page
    console.log(window.location.pathname);
}

See MDN info on window.location.pathname.

Bradley Flood
  • 10,233
  • 3
  • 46
  • 43
15

You can find out if you're on the homepage by comparing href to origin:

window.location.origin == window.location.href

To get the query parameters you can use the answer here: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Mataniko
  • 2,212
  • 16
  • 18
  • 4
    I noticed that href can return the url with a trailing slash, eg mysite.com/ , while origin is without a slash... – giorgio79 Jul 04 '14 at 14:18
  • 1
    This answer is wrong: it fails because `window.location.origin` is `http://www.mywebsite.com` while `window.location.href` is `http://www.mywebsite.com/` – Luca Natali May 30 '18 at 08:31
6

Take a look at the window.location docs , the information you want is in location.search , so a function to check it could just be:

function url_has_vars() {
   return location.search != "";
}
Nelson
  • 49,283
  • 8
  • 68
  • 81
3

if current url is xxxxx.com something like that, then xxx

if (window.location.href.split('/').pop() === "") { 
    //this is home page
}
benlo335
  • 31
  • 1
2

You need a query string searching function to do this..

function getParameterByName(name) {  
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");  
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),  
        results = regex.exec(location.search);  
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));  
}

Before redirect check the query string and match with the expected value and redirect as requirement.

Sudip Pal
  • 2,041
  • 1
  • 13
  • 16
1

Taking inspiration from Mataniko suggestion, I slightly modified it to fix its issue:

if (window.location.origin + "/" == window.location.href ) {
  // Index (home) page
  ...
}

In this way, this test pass only in homepage

Luca Detomi
  • 5,564
  • 7
  • 52
  • 77