3

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

Badacadabra
8,5457 gold badges33 silver badges54 bronze badges
asked Apr 20, 2015 at 15:43

1 Answer 1

6

The easiest would probably be

var sPageURL = window.location.href.split('/').pop();
answered Apr 20, 2015 at 15:44
Sign up to request clarification or add additional context in comments.

2 Comments

That's a very good answer. And it works in this situation. However problems may arise in the future if I use more than 1 variable. Thanks.
Then you'd have to write code that gets those variables based on where in the URL they are. There is no magic function.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.