0

I am creating a script which detects and returns the page name. However when there is a query string, it doesn't return the value I want for the "url_segment".

Can somebody show me how I can remove the query string and return the values for the variables "url" and "url_segment"

// http://test.com/action
// http://test.com/action/all
// http://test.com/action/all?page=2

function return_page_name()
{
    var url = $(location).attr("href").split("/")[3]; // returns "action"
    var url_segment = $(location).attr("href").split("/")[4]; // returns "all" (if selected)

    if(url === "")
    {
        page = "homepage";
    }
    else if(url === "signup") {
        page = "sign-up";
    }

    return page;
}
  • Avoid using jQuery in this case, it's not necessary. You can easily get(and parse) the pathname using `window.location.pathname`. Split it like you're doing now and get the elements you need. – Niccolò Campolungo Aug 27 '13 at 11:38
  • Assuming `location` is actually [`window.location`](https://developer.mozilla.org/en-US/docs/Web/API/window.location), there's no need to wrap it in jQuery. – André Dion Aug 27 '13 at 11:38
  • http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page – Bahattin Çiniç Aug 27 '13 at 11:39

2 Answers2

0

You can use this code:

function Q() {
    var q={};
    var a=window.location.search.substring(1);
    var b=a.split("&");
    for (var i=0;i<b.length;i++) {
        var c=b[i].split("=");
        q[c[0]]=c[1];
    }
    return q;
}

So that you can execute it and get an Object which contains the query strings like you have with PHP.

Ozzy
  • 8,244
  • 7
  • 55
  • 95
0

See window.location.pathname

function getLastUrlSegment() {
    return window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
}

 // http://test.com/action
window.location.pathname == '/action'
getLastUrlSegment() == 'action'

// http://test.com/action/all
window.location.pathname == '/action/all'
getLastUrlSegment() == 'all'

// http://test.com/action/all?page=2
window.location.pathname == '/action/all'
getLastUrlSegment() == 'all'
André Dion
  • 21,269
  • 7
  • 56
  • 60