/ Published in: JavaScript
two awesome bits: using ''.replace() perform an action (other than replacing it) on some text, and a simple way to concatenate strings with a separator (retardedly simple but it always confuses me)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var q = 'foo=1&blah=a&foo=2&foo=3&blah=b' function compress(data){ var q = {}, ret = ''; data.replace(/([^=&]+)=([^&]*)/g, function(m, key, value){ q[key] = (q[key] ? q[key] + ',' : '') + value; }); for ( var key in q ) ret = (ret ? ret + '&' : '') + key + '=' + q[key]; return ret; } console.log(compress(q))
URL: http://ejohn.org/blog/search-and-dont-replace/