201

Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($) function so I can do something like this:

$('?search').val(); 

Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test.

I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.

5
  • 4
    Asked and answered: stackoverflow.com/questions/901115/… Commented Oct 11, 2011 at 20:08
  • 1
    @NicoWesterdale - I went through that link, but didn't see any answers that solve this particular question. He said he wants exactly as above. Commented Oct 11, 2011 at 20:12
  • 2
    I don't think you can do this, a string passed in gets parsed by sizzler, then resolved to an array of DOM objects. You can extend the matcher to provide custom filters, but you can't have a jquery object based on a string. Commented Oct 11, 2011 at 20:24
  • 6
    Isn't $ overloaded enough? Commented Oct 11, 2011 at 20:30
  • 1
    @mrtsherman Look at the getParameterByName() function in the link I provided. No you can't do it from directly within a $ prompt, but that's not what jQuery selectors are for. He's just selecting part of a URL string, not trying to access part of the DOM which is what $() does. It's a totally different thing. If you really wanted to use jQuery you could write a plugin that used this syntax: $.getParameterByName(param), there's an example further down on that page I linked to that does exactly that. Kinda pointless though. Commented Oct 13, 2011 at 13:54

10 Answers 10

173

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')); // 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"

UPDATE (03/21/24) : All Major Browsers Now Supported

URLSearchParams is now supported by all major browsers

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
Sign up to request clarification or add additional context in comments.

8 Comments

is URLSearchParams supported by all browsers?
Oops! ohh man, IE is not supported !! I have just tested on it. While Chrome, FF, Safari has no issue.
@divine - There is a polyfill for URLSearchParams here: github.com/WebReflection/url-search-params
If you add a polyfill for unsupported browsers this URLSearchParams solution works well. github.com/ungap/url-search-params
wont work with say https://mytest.com/bippo/#/?utm_source=teeest or https://mytest.com/bippo/#/url/?utm_source=teeest
|
114

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.

9 Comments

It's not common but it is valid to use semi-colons instead of ampersands in the query parameters.
@Muhd - It's "valid" to use any delimiter you like in a querystring as long as your code understands it. But, when a form is submitted, the form fields are submitted as name=value pairs, separated by &. If your code is using a custom querystring format, obviously, you'll need to write a custom querystring parser wherever the querystring is consumed, whether on the server or the client.
@nick - Interesting. But their suggestion for HTTP servers to treat semi-colons as ampersands only serves to make HTML prettier when using a link to mimic a form submission. It is just a suggestion and is non-standard. A standard form GET submission is encoded as application/x-www-form-urlencoded, with values separated by &. My code handles that standard. Custom url structures such as the one you linked will need a custom parser server-side and client-side. Regardless, adding such capability to my code above would be trivial.
@gilly indeed - if you want portable code you need to support both
Add "i" to the RegExp() so the key can be case insensitive: new RegExp("[?&]"+key+"=([^&]+)(&|$)", "i"));
|
96

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')

10 Comments

Nice. And the code is in the public domain so you don't even have to include the comments.
Good solution but won't work if you happen to be testing via file://
Whats that have to do anything with, @kampsj
Hi @kampsj, testing with file:// protocol will cause a lot more stuff not to work. You can create a very quick and easy static HTML server with node.js. stackoverflow.com/questions/16333790/…
This plugin is no longer maintained and the author itself is suggesting to use other plugins instead.
|
95

Found this gem from our friends over at SitePoint. https://www.sitepoint.com/url-parameters-jquery/.

Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.

//URL is http://www.example.com/mypage?ref=registration&[email protected]

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //[email protected]

Use as you will.

11 Comments

Great. Thanks! I don't think you need the last closing brace tag though.
You should use window.location.search instead of .href -- otherwise, good.
Instead of results[1] || 0, you must do if (results) {return results[1]} return 0; bcoz query parameters may not be present at all. And modifying will handle all generic cases.
What do you do if you have something like https://example.com/?c=Order+ID ? That plus sign still remains on this function.
"Using PURE jQuery." This solution doesn't actually use any JQuery. It only extends JQuery with what could just as easily be a stand alone function.
|
48

This isn't my code sample, but I've used it in the past.

//First Add this to extend jQuery

    $.extend({
      getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });

    //Second call with this:
    // Get object of URL parameters
    var allVars = $.getUrlVars();

    // Getting URL var by its name
    var byName = $.getUrlVar('name');

3 Comments

You shouldn't split on '=', it's technically okay to have a second equals sign in the value of any key/value pair. -- Only the first equals sign you encounter (per key/value pair) should be treated as a delimiter. (Also, the equals sign isn't strictly required; it's possible to have a key with no value.)
Clean solution. Worked perfectly in my case.
$.extend({ getUrlVars: function(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); var k = hash.shift(); vars.push(k); vars[k] = hash.join(""); } return vars; }, getUrlVar: function(name){ return $.getUrlVars()[name]; } });
17

I wrote a little function where you only have to parse the name of the query parameter. So if you have: ?Project=12&Mode=200&date=2013-05-27 and you want the 'Mode' parameter you only have to parse the 'Mode' name into the function:

function getParameterByName( name ){
    var regexS = "[\\?&]"+name+"=([^&#]*)", 
  regex = new RegExp( regexS ),
  results = regex.exec( window.location.search );
  if( results == null ){
    return "";
  } else{
    return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}

// example caller:
var result =  getParameterByName('Mode');

1 Comment

If your name has no junk, you can drop the first regex and it make more sense to start from location.search
8

Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).

function parseQueryString () {
  var parsedParameters = {},
    uriParameters = location.search.substr(1).split('&');

  for (var i = 0; i < uriParameters.length; i++) {
    var parameter = uriParameters[i].split('=');
    parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
  }

  return parsedParameters;
}

3 Comments

I haven't seen any erroring using this code. What browser are you using? I've tested it against current Firefox, Chrome, and Safari.
Yeah sorry I read it wrong. I thought I saw it call a method on something that was returning undefined. So really it's just running once when it doesn't have to. When search is "". And you get {"": "undefined"}
Yeah. That could probably use some refining.
3
function parseQueryString(queryString) {
    if (!queryString) {
        return false;
    }

    let queries = queryString.split("&"), params = {}, temp;

    for (let i = 0, l = queries.length; i < l; i++) {
        temp = queries[i].split('=');
        if (temp[1] !== '') {
            params[temp[0]] = temp[1];
        }
    }
    return params;
}

I use this.

Comments

2

Written in Vanilla Javascript

     //Get URL
     var loc = window.location.href;
     console.log(loc);
     var index = loc.indexOf("?");
     console.log(loc.substr(index+1));
     var splitted = loc.substr(index+1).split('&');
     console.log(splitted);
     var paramObj = [];
     for(var i=0;i<splitted.length;i++){
         var params = splitted[i].split('=');
         var key = params[0];
         var value = params[1];
         var obj = {
             [key] : value
         };
         paramObj.push(obj);
         }
    console.log(paramObj);
    //Loop through paramObj to get all the params in query string.

Comments

1

function getQueryStringValue(uri, key) {        
        var regEx = new RegExp("[\\?&]" + key + "=([^&#]*)");        
        var matches = uri.match(regEx);
        return matches == null ? null : matches[1];
}

function testQueryString(){
   var uri = document.getElementById("uri").value;
   var searchKey = document.getElementById("searchKey").value;
   var result = getQueryStringValue(uri, searchKey);
   document.getElementById("result").value = result;
}
<input type="text" id="uri" placeholder="Uri"/>
<input type="text" id="searchKey" placeholder="Search Key"/>
<Button onclick="testQueryString()">Run</Button><br/>

<input type="text" id="result" disabled placeholder="Result"/>

Comments

Your Answer

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.