How to Create Query Parameters in JavaScript

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 can I add or update a query string parameter?

I wrote the following function which accomplishes what I want to achieve:

function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}

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.

Add multiple query parameters in URI for each element

When in need of query params with the same name (array-like) use a params format like: ?a[]=1&a[]=2. Just like you would when using checkboxes with the same name or a select of type multiple.

Sites only:

?site[]=x&site[]=y

Sites with dates:

?site[]=x&site[]=y&start_at[]=x1&end_at[]=x2&start_at[]=y1&end_at[]=y2

the only caveat is to respect the order: if you start with site "X", then the first pair of start/end dates should be the ones for site "X".

More readable:

?site[]=x
&site[]=y
&start_at[]=x1
&end_at[]=x2
&start_at[]=y1
&end_at[]=y2

Another valid example with different order:

?site[]=x
&start_at[]=x1
&end_at[]=x2
&site[]=y
&start_at[]=y1
&end_at[]=y2

Then on the back-end side, knowing that the order is predictable, you can get all your variables inside a single loop of sites length.

Also, by using the above suggestion you can use N sites with their respective start/end pairs.

Example:

// Helper functions:

const objectsToFormData = (...objects) => {
const FD = new FormData();
objects.forEach(obj => {
Object.entries(obj).forEach(([k, v]) => FD.append(k, v));
});
return FD;
};

const formDataToQueryString = (FD) =>
new URLSearchParams(FD).toString();

// Task:

const data_1 = {
"site[]": location.origin,
"start_at[]": "2022-11-02",
"end_at[]": "2022-06-25",
};

const data_2 = {
"site[]": "https://example.com",
"start_at[]": "2021-09-20",
"end_at[]": "2022-07-13",
};

const formData = objectsToFormData(data_1, data_2);
const queryString = formDataToQueryString(formData);

console.log(queryString);
console.log(decodeURIComponent(queryString));

Change URL parameters and specify defaults using JavaScript

To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.

You can use query-string as follows:

// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);

Build query string from parameters object

There is a nice solution as of 1.4+. You can build a query string from a parameters object with $httpParamSerializer :

var qs = $httpParamSerializer(params);

See docs here

Default $http params serializer that converts objects to strings
according to the following rules:

{'foo': 'bar'} results in foo=bar
{'foo': Date.now()} results in foo=2015-04-01T09%3A50%3A49.262Z (toISOString() and encoded representation of a Date object)
{'foo': ['bar', 'baz']} results in foo=bar&foo=baz (repeated key for each array element)
{'foo': {'bar':'baz'}} results in foo=%7B%22bar%22%3A%22baz%22%7D" (stringified and encoded representation of an object)
Note that serializer will sort the request parameters alphabetically.

How to convert URL parameters to a JavaScript object?

In the year 2021... Please consider this obsolete.

Edit

This edit improves and explains the answer based on the comments.

var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

Example

Parse abc=foo&def=%5Basf%5D&xyz=5 in five steps:

  • decodeURI: abc=foo&def=[asf]&xyz=5
  • Escape quotes: same, as there are no quotes
  • Replace &: abc=foo","def=[asf]","xyz=5
  • Replace =: abc":"foo","def":"[asf]","xyz":"5
  • Suround with curlies and quotes: {"abc":"foo","def":"[asf]","xyz":"5"}

which is legal JSON.

An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:

var search = location.search.substring(1);
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

Example

search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";

gives

Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}

Original answer

A one-liner:

JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')

How to serialize an Object into a list of URL query parameters?

var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}

Example: http://jsfiddle.net/WFPen/



Related Topics



Leave a reply



Submit