Monday, 5 June 2017

url - How can I get query string values in JavaScript?




Is there a plugin-less way of retrieving query string values via jQuery (or without)?




If so, how? If not, is there a plugin which can do so?


Answer



Update: Sep-2018



You can use URLSearchParams which is simple and has decent (but not complete) browser support.



const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');



Original



You don't need jQuery for that purpose. You can use just some pure JavaScript:



function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;

if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}


Usage:



// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)

var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)



Note: If a parameter is present several times (?foo=lorem&foo=ipsum), you will get the first value (lorem). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp






This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...