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: .
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.
510 Answers
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 : 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 6Why 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, " ")); } 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, " ")); }); 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.
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')
Found this gem from our friends over at SitePoint. .
Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.
//URL is $.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')); // Use as you will.
10This 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'); 3I 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'); 1Building 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; } 3function 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.
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. 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" placeholder="Uri"/> <input type="text" placeholder="Search Key"/> <Button onclick="testQueryString()">Run</Button><br/> <input type="text" disabled placeholder="Result"/>