125

Possible Duplicate:
How to get “GET” request parameters in JavaScript?
jQuery querystring
How can I get query string values in JavaScript?

Javascript does not provide a core method to do that, so how to do it?

1

1 Answer 1

455
function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');
18
  • 1
    Thanks for a great answer. Added an edit to it to take into account the edge case of parameters with no values. May 27, 2014 at 10:35
  • 3
    @DeanMeehan awesome if it "just works" but I would not say that it is a simple solution considering the readability of regex expressions
    – Adriano
    Oct 30, 2014 at 14:59
  • 3
    Does this work if there is a hash tag in the URI? If there is a #something in Chrome, then you have to use window.location.hash instead of window.location.search... Jan 8, 2015 at 21:54
  • 14
    Would have upvoted if a) explanation of what's going on and b) passes JSHint validation: currently, the [, ""] construction is invalid
    – Phortuin
    Feb 2, 2015 at 13:08
  • 1
    How can you get values for an array parameter such as test.com?arr[]=vxcbcvb%20cvbvbcvb
    – mpora
    Sep 14, 2015 at 16:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.