Get query string parameters url values with jQuery / Javascript (querystring) Get query string parameters url values with jQuery / Javascript (querystring) javascript javascript

Get query string parameters url values with jQuery / Javascript (querystring)


Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?

function qs(key) {    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));    return match && decodeURIComponent(match[1].replace(/\+/g, " "));}

http://jsfiddle.net/gilly3/sgxcL/

An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):

location.queryString = {};location.search.substr(1).split("&").forEach(function (pair) {    if (pair === "") return;    var parts = pair.split("=");    location.queryString[parts[0]] = parts[1] &&        decodeURIComponent(parts[1].replace(/\+/g, " "));});

http://jsfiddle.net/gilly3/YnCeu/

This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.


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 URL has "?post=1234&action=edit"var urlParams = new URLSearchParams(window.location.search);console.log(urlParams.has('post')); // trueconsole.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"

UPDATE : IE is not supported

use this function from an answer below instead of URLSearchParams

$.urlParam = function (name) {    var results = new RegExp('[\?&]' + name + '=([^&#]*)')                      .exec(window.location.search);    return (results !== null) ? results[1] || 0 : false;}console.log($.urlParam('action')); //edit


JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use

$.url().param('search');

This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.

Or you can use js-url instead. Its quite similar to the one below.

So you can access the query param like $.url('?search')