[Solved-5 Solutions] Query string values in javaScript - javascript Tutorial
Problem:
How to get a query string in javascript ?
Solution 1:
Using URLSearchParams is simple.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
This code don't need jQuery. So we can use 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, " "));
}
Use this code:
// 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), to get the first value as (lorem).
This function is case-sensitive.
Solution 2:
Repeating the regular expression search every time the script wants to access a parameter is completely. One single function to split up the parameters into an associative-array style object. Not working with the HTML 5 History API, this is only necessary once per page load.
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty
Result:
urlParams = {
enc: " Hello ",
i: "main",
mode: "front",
sid: "de8d49b78a85a322c4155015fdce22c4",
empty: ""
}
alert(urlParams["mode"]);
// -> "front"
alert("empty" in urlParams);
// -> true
To handle style-array query strings.
Solution 3:
You can use this:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
Solution 4:
- To retrieve all parts of URL, including anchor, host, etc.
- It can be used with or without jQuery.
var url = $.url('http://wikitechy.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://wikitechy.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
The jQuery plugin is different on elements.
var url = new URI('http://wikitechy.com/folder/dir/index.html?item=value'); // plain JS version
url.protocol(); // returns 'http'
url.path(); // returns '/folder/dir/index.html'
Solution 5:
jQuery plugin:
;(function ($) {
$.extend({
getQueryString: function (name) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[name];
}
});
})(jQuery);
The syntax is:
var someVar = $.getQueryString('myParam');