Search code examples
javascriptjqueryif-statementpathname

If statement not work jquery


I have this url:

csumb/index.php?page=consultanta 

I try to compare 2 links but this code do the same thing if I change my link and I refresh the page.

var pathname = window.location.pathname;
var a = "csumb/index.php?page=consultanta";

if(pathname == a) {
    $("body").html("rahat");
}

Solution

  • There's multiple parts to location (or window.location, to use the literal reference):

    https://packagist.org/search/?search_query%5Bquery%5D=symfony

    Using console.log(location) directly into the Chrome console, it gives the following properties (plus some other stuff):

    hash: ""
    host: "packagist.org"
    hostname: "packagist.org"
    href: "https://packagist.org/search/?search_query%5Bquery%5D=symfony&page=4"
    origin: "https://packagist.org"
    pathname: "/search/"
    port: ""
    protocol: "https:"
    search: "?search_query%5Bquery%5D=symfony&page=4"
    

    What you're really after is:

    var pathname = location.pathname + location.search;
    var a = "/csumb/index.php?page=consultanta";
    //       ^ Note the / at the beginning
    

    The filename, if in the URL, will be in location.pathname, so index.php will not need to be added separately either.