-2

I want to stringify an object into a query string.

For example,

{ hello: '123', goodbye: "789" }

Would give me...

hello=123&goodbye=789
2

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for answering the actual question.
3

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.