I want to stringify an object into a query string.
For example,
{ hello: '123', goodbye: "789" }
Would give me...
hello=123&goodbye=789
I want to stringify an object into a query string.
For example,
{ hello: '123', goodbye: "789" }
Would give me...
hello=123&goodbye=789
There is an excellent URL library, URL.js which works pretty much as you describe for queries.
For your example, the code would be:
URI().addSearch({ hello: '123', goodbye: "789" }).toString()
This produces the result with a pre-pended ?
, but it comes in extremely handy for constructing & manipulating real URLs.
If case if you use jQuery in your project you don't need a lib for this:
$.param({ hello: '123', goodbye: "789" })
But since there is no jQuery tag, take a look at Barney
answer, this is probably what you need.
Here is a code sample for simple cases:
var params={ hello: '123', goodbye: "789" },
pairs=[];
for (var key in params) {
if (params.hasOwnProperty(key)) {
pairs.push(key+"="+encodeURIComponent(params[key]));
}
};
var qs=pairs.join("&");
For more complex scenarios you might want to use a library like URLjs as suggested in other replies.