How to create query parameters in Javascript?
Is there any way to create the query parameters for doing a GET request in JavaScript?
Just like in Python you have urllib.urlencode()
, which takes in a dictionary (or list of two tuples) and creates a string like 'var1=value1&var2=value2'
.
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);
URLSearchParams has increasing browser support.
const data = {
var1: 'value1',
var2: 'value2'
};
const searchParams = new URLSearchParams(data);
// searchParams.toString() === 'var1=value1&var2=value2'
Node.js offers the querystring module.
const querystring = require('querystring');
const data = {
var1: 'value1',
var2: 'value2'
};
const searchParams = querystring.stringify(data);
// searchParams === 'var1=value1&var2=value2'
functional
function encodeData(data) {
return Object.keys(data).map(function(key) {
return [key, data[key]].map(encodeURIComponent).join("=");
}).join("&");
}
Zabba has provided in a comment on the currently accepted answer a suggestion that to me is the best solution: use jQuery.param().
If I use jQuery.param()
on the data in the original question, then the code is simply:
const params = jQuery.param({
var1: 'value',
var2: 'value'
});
The variable params
will be
"var1=value&var2=value"
For more complicated examples, inputs and outputs, see the jQuery.param() documentation.