0

I am trying to do the opposite of this question, namely, convert a JavaScript object into the query at the end of a url. This is for a potentially huge, and completely randomized string in terms of keys/values. For example,

activity = {myKey:"randomString"}

'<img src="images/image.gif?' + activity + '">'

Would give me back:

<img src='images/image.gif?{myKey:"randomString"}'>
Community
  • 1
  • 1
maudulus
  • 10,627
  • 10
  • 78
  • 117
  • duplicate of [http://stackoverflow.com/q/5505085/798682](http://stackoverflow.com/q/5505085/798682)? i see your example is different, but your "opposite this question" matches. – mattr Nov 03 '14 at 22:08

2 Answers2

1
var queryValues={
  param:"0",
  s:"stack",
  o:"overflow",
  myKey:"randomString"
};
var qparts=Object.keys(queryValues).map(function(k){
  return [k,queryValues[k]].map(encodeURIComponent).join("=");
});
var queryString=qparts.length?"?"+qparts.join("&"):"";


/*
queryString:
?param=0&s=stack&o=overflow&myKey=randomString
*/

Then modify the original url by concatenating with the queryString. Like so:

images/image.gif?param=0&s=stack&o=overflow&myKey=randomString

Also, from your question, you wanted a url that looks like this:

images/image.gif?{myKey:"randomString"}

Which appears malformed and not quite the opposite of what was posted in the other question you linked to. So I gave you a snippet to produce a well-formed query string instead.

jongo45
  • 3,020
  • 2
  • 16
  • 12
0
var myURL = '<img src="images/image.gif?' + JSON.stringify(activity) + '">';