Get Query String Parameters with JavaScript

By  on  

Query string parameters have been incredibly useful on the server side since the internet took liftoff, but it wasn't until AJAX-driven web apps became popular that we relied too much on them on the client side. Not only do we grab parameter values but we also modify them dynamically with the History API, so these parameters play a major role outside of the initial page load.

We've always been able to get the full query string via the window.location.search property:

console.log(window.location.search);
// "?post=1234&action=edit"

...but in a world of setters, getters, and JSON, there must be a better way to get values than parsing a string, right? After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

URLSearchParams also provides familiar Object methods like keys(), values(), and entries():

var keys = urlParams.keys();
for(key of keys) { 
  console.log(key); 
}
// post
// action

var entries = urlParams.entries();
for(pair of entries) { 
  console.log(pair[0], pair[1]); 
}

URLSearchParams reminds me a lot of the classList API -- very simple methods yet very useful.

JavaScript Fallback

While URLSearchParams is ideal, not all browsers support that API. There's a polyfill available but if you want a tiny function for basic query string parsing, the following is a function stolen from the A-Frame VR toolkit which parses the query string to get the key's value you'd like:

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

With the function above, you can get individual parameter values:

getUrlParameter('post'); // "1234"
getUrlParameter('action'); // "edit"

Anyways, enjoy this function -- you'll find yourself needing it more than you think!

Recent Features

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

  • By
    Create Spinning Rays with CSS3 Animations & JavaScript

    Thomas Fuchs, creator of script2 (scriptaculous' second iteration) and Zepto.js (mobile JavaScript framework), creates outstanding animated elements with JavaScript.  He's a legend in his own right, and for good reason:  his work has helped to inspire developers everywhere to drop Flash and opt...

  • By
    Image Manipulation with PHP and the GD Library

    Yeah, I'm a Photoshop wizard. I rock the selection tool. I crop like a farmer. I dominate the bucket tool. Hell, I even went as far as wielding the wizard wand selection tool once. ...OK I'm rubbish when it comes to Photoshop.

Discussion

  1. So on a tiny snippet like this, I wonder if caching the generated RegExp would help or hurt perf:

    https://jsfiddle.net/0p17799t/

    • MaxArt

      Honestly, why are you even thinking about performance for something like that? It’s not like something you need to do hundreds of times every second.

  2. MaxArt

    > I’d much rather the search property be a key: value object.

    Well, while something like PHP’s $_GET would be useful, it’s also true that query strings aren’t alwas URL-encoded maps.
    I’d love to have an additional property in location for that, though.

  3. I’ve been using the following snippet for a while:

    function getQueryVariable(variable) {
    	var query = window.location.search.substring(1);
    	var vars = query.split("&");
    	for (var i=0;i<vars.length;i++) {
    		var pair = vars[i].split("=");
    		if(pair[0] == variable){return pair[1];}
    	}
    	return(false);
    }
    
  4. Tim Snadden

    lil’-uri does this quite nicely https://github.com/lil-js/uri

  5. I built a tiny function to do this: https://github.com/travishorn/qs

    Include qs.js in your HTML file, then call

    qs.get()

    . The output is:

    {
      post: "1234",
      action: "edit"
    }
  6. Too bad you can’t get object, with all parameters, with this API and you need to know what parameter to get.

  7. Forgive me if I am wrong, but i am fairy certain the .exec method is not the way to do this anymore.

  8. Tbox

    I am using AddToAny for referral program.
    I can’t figure how to custom a specific url.

    The

    window.location.href

    url is : https://www.mywebsite.com/bravo/?r=number
    (number is variable but always a number)

    I would like to use this

    window.location.href

    url to custom the AddToAny share link. What I need as a restult is:
    https://www.mywebsite.com/?r=number

    Do you think it is possible using Javascript

  9. Steve

    In my case I can’t use window.location.search because
    I am doing an ajax load into div.

    $( "#result" ).load( "service.html?param1=1&param2=2");
    

    In this case how can I read the param1 and 2 values when I am inside service.html?

  10. Kim Damsleth

    Thank you for this function. I really enjoy using it! I would like to use it even more when time allows.

  11. Brandon

    Joe’s code
    (found here & above in his comment) seems to be better for performance from what I can see.

    function getQueryVariable(variable) {
    	var query = window.location.search.substring(1);
    	var vars = query.split("&");
    	for (var i=0;i<vars.length;i++) {
    		var pair = vars[i].split("=");
    		if(pair[0] == variable){return pair[1];}
    	}
    	return(false);
    }
  12. Matt Doran

    URLSearchParams isn’t supported by IE so who can really use it

  13. Tim Anderson

    @Matt Doran – IE is pretty much dead. ~2.2% market share at the time of this comment. Microsoft Edge is its successor – or use older browser technologies to achieve roughly equivalent functionality.

  14. Vince

    I’m a total novice when it comes to understanding the logic behind how javascript parses values and the ‘order of things’ but here’s what I’m trying to do and perhaps someone can point me in the right direction?

    I have a form that redirects on submit to a ‘thank you’ url like

    http://www.domain.com/?CID=number (number is always a random number)

    I need to extract ‘number’ and insert it into an pixel img URL such as:

    http://www.otherdomain.com/sale.cfm?tracking=number

    What I’ve tried is:

    var urlParams = new URLSearchParams(window.location.search);
    var customerID = console.log(urlParams.get('CID'));
    var some_IMG = document.createElement("IMG"); shrsl_IMG.src = "https://www.otherdomain.com/sale.cfm?tracking="+customerID+"";
    document.body.appendChild(some_IMG);
    

    and then add

    
    

    Yet I always get an undefined result.

    Any help is appreciated!

  15. Since it seemed like everyone kept wanting dictionary access here’s one I wrote up that can return a whole dictionary of query parameters or a single parameter with optional no-decode.

    https://codepen.io/codyswartz/pen/LYpdgJE

    For example, if you add some query parameters to this page and try it out:
    https://davidwalsh.name/query-string-javascript?test=hello&datBoi=yep+its%20me%2B

    getUrlParameters()
    // {test: "hello", datBoi: "yep its me+"}
    
    getUrlParameters().datBoi
    // "yep its me+"
    
    getUrlParameters(false, false)
    // {test: "hello", datBoi: "yep+its%20me%2B"}
    
    getUrlParameters('datBoi')
    // "yep its me+"
    
    getUrlParameters('datBoi', false)
    // "yep+its%20me%2B"
    
  16. Mani
    var keys = urlParams.keys();
    for(key of keys) { 
      console.log(key); 
    }
    // post
    // action
    
    var entries = urlParams.entries();
    for(pair of entries) { 
      console.log(pair[0], pair[1]); 
    }
    

    This technique is full Branded, Thanks a lot

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!