How to Get Url Parameters with JavaScript

Get the values from the GET parameters (JavaScript)

JavaScript itself has nothing built in for handling query string parameters.

Code running in a (modern) browser can use the URL object (a Web API). URL is also implemented by Node.js:

// You can get url_string from window.location.href if you want to work with
// the URL of the current page
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

How can I get query string values in JavaScript?

Update: Jan-2022

Using Proxy() is faster than using Object.fromEntries() and better supported

const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"

Update: June-2021

For a specific case when you need all query params:

const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

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 = 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

NOTE: If you're getting a no-useless-escape eslint error, you can replace name = name.replace(/[\[\]]/g, '\\$&'); with name = name.replace(/[[\]]/g, '\\$&').


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

How to get URL parameter using jQuery or plain JavaScript?

Best solution here.

var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;

for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');

if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};

And this is how you can use this function assuming the URL is,

http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');

How to create query parameters in Javascript?

Here you go:

function encodeQueryData(data) {
const ret = [];
for (let d in data)
ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
return ret.join('&');
}

Usage:

const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };
const querystring = encodeQueryData(data);

Adding a parameter to the URL with JavaScript

A basic implementation which you'll need to adapt would look something like this:

function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);

// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = document.location.search.substr(1).split('&');
let i=0;

for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}

if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}

// can return this or...
let params = kvp.join('&');

// reload page with new params
document.location.search = params;
}

This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match


the slow regex method I benchmarked against for completions sake (approx +150% slower)

function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);

var s = document.location.search;
var kvp = key+"="+value;

var r = new RegExp("(&|\\?)"+key+"=[^\&]*");

s = s.replace(r,"$1"+kvp);

if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};

//again, do what you will here
document.location.search = s;
}

How to get URL parameters with Javascript?

function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

Getting the url parameters inside the html page

A nice solution is given here:

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​

And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample:

var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');`

How to obtain the query string from the current URL with JavaScript?

Have a look at the MDN article about window.location.

The QueryString is available in window.location.search.

If you want a more convenient interface to work with, you can use the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

The URLSearchParams interface is now widely adopted in browsers (95%+ according to Can I Use), but if you do need to support legacy browsers as well, you can use a polyfill.



Related Topics



Leave a reply



Submit