How to create query parameters in Javascript?
Solution 1
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);
Solution 2
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'
Solution 3
functional
function encodeData(data) {
return Object.keys(data).map(function(key) {
return [key, data[key]].map(encodeURIComponent).join("=");
}).join("&");
}
Solution 4
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.
Solution 5
ES2017 (ES8)
Making use of Object.entries()
, which returns an array of object's [key, value]
pairs. For example, for {a: 1, b: 2}
it would return [['a', 1], ['b', 2]]
. It is not supported (and won't be) only by IE.
Code:
const buildURLQuery = obj =>
Object.entries(obj)
.map(pair => pair.map(encodeURIComponent).join('='))
.join('&');
Example:
buildURLQuery({name: 'John', gender: 'male'});
Result:
"name=John&gender=male"
Related videos on Youtube
cnu
A computer programmer, recently became an entrepreneur ready to make my own dent.
Updated on February 02, 2022Comments
-
cnu over 2 years
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'
.-
user202729 over 2 yearsReverse question: url - How can I get query string values in JavaScript? - Stack Overflow
-
-
troelskn over 15 yearsWhen iterating with
for
, use hasOwnProperty to ensure interoperability. -
AnthonyWJones over 15 yearsencodeURIComponent handles this and doesn't incorrectly use + for a space.
-
Shog9 over 15 years@troelskn, good point... although in this case, someone would have to be extending Object.prototype to break it, which is a pretty bad idea to start with.
-
Cesar Canassa over 12 years@Shog9 Why is it a bad ideia?
-
Shog9 over 12 years@Cesar, see: stackoverflow.com/questions/3832617/…**
-
Akseli Palén over 11 yearsNice one! .map() has been implemented in JavaScript 1.6 so almost all browsers, even the granny ones support it. But as you can guess IE does not except IE 9+. But do not worry, there is a workaround. Source: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
-
Tim almost 9 yearsjQuery.param() takes object and transform it to GET query string (this function better matches the question).
-
dylanh724 over 6 years
var data = { bloop1: true, bloop2: "something" }; var url = "https://something.com/?"; var params = encodeData(data); var finalUrl = url + params; // Is this the right use?
Should producehttps://www.something.com/?bloop1=true&bloop2=something
? -
eaorak about 6 yearsI've later realized that it's actually a slightly different version of @manav's response below. But anyway, it could still be preferable for ES6 syntax.
-
Przemek almost 6 yearsFirst of all, you are not encoding the keys. Also, you should use
encodeURIComponent()
instead ofencodeURI
. Read about the difference. -
Przemek almost 6 years@DylanHunt: Yup…
-
kano over 4 yearsDefinitely the clean and modern approach. You can also later freely call
searchParams.append(otherData)
-
masterxilo about 4 yearsDownvote because I have no idea whether this solution acts according to the specification and will always work. Prefer the standard URLSearchParams that is now available. OP please consider retreating this outdated answer.
-
masterxilo about 4 yearsVery unspecific answer.
-
wrkwrk over 3 yearsURLSearchParams will parse White space as '+' instead of '%20'. For example,
new URLSearchParams({ abc: 'a b c' }).toString()
result in'abc=a+b+c'
-
hanshenrik over 3 yearsthis is insufficient.
encodeQueryData({foo:{bar:123}})
returnsfoo=%5Bobject%20Object%5D
, but the correct return value would befoo%5Bbar%5D=123
-
hanshenrik over 3 yearsthis is insufficient.
encodeData({foo:{bar:123}})
returnsfoo=%5Bobject%20Object%5D
, but the correct return value would befoo%5Bbar%5D=123
-
hanshenrik over 3 yearsthis is an improvement, yes, but it's still insufficient:
encodeQueryData({foo:{bar:123}})
returnsfoo[]=123
, but the correct return value would befoo%5Bbar%5D=123
-
francistheturd over 2 yearsHow is it that in 2021 there is not a more standardized way of achieving this? For example, what about adding
?
only whensearchParams
are not blank. -
LP Square about 2 yearsThis is the new correct way.
function encodeQueryData(data) { return new URLSearchParams(data).toString(); }