Prescient
Prescient

Reputation: 1061

How to get query string parameter from SEO-friendly URL?

I switched from using normal URL parameters to SEO-friendly URLs. For example, I have gone from this...

http://www.example.net/mypage.aspx?id=1

... to this:

http://www.example.net/mypage/1

Using JavaScript or jQuery, what would be the best way to get the id variable of 1?

I currently use a function like this:

// get the values from the query string.
function GetQueryStringParams(sParam) {
var sPageURL = window.location.search.substring(1);

var sURLVariables = sPageURL.split('&');

for (var i = 0; i < sURLVariables.length; i++) {
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam) {
        return sParameterName[1];
    }
}

Is there a better way or am I stuck splitting the URL via the /?? And how would you handle multiple parameters?

http://www.example.net/mypage/1/2/3/4/5

Upvotes: 3

Views: 3152

Answers (1)

adeneo
adeneo

Reputation: 318182

The easiest would probably be

var sPageURL = window.location.href.split('/').pop();

Upvotes: 6

Related Questions