JavaScript: Search and don't replace
ejohn.org
ejohn.org
Arguing that this is a better solution on the grounds of optimization would be salient if this were a function likely to be called thousands of times on a large data set. I just can't imagine that being the case in this instance.
I subscribe to the idea that when given the choice between 'clever' optimized code, and code which is instantly readable and maintainable, it's best to opt for the latter – unless you're trying to resolve an execution bottleneck.
The version eventually created in the comments seemed much better:
function compress(data){
var match = [], q = {}, ret = "", re = /([^=&]+)=([^&]*)/g;
while (match = re.exec(data)){
q[match[1]] = (q[match[1]] ? q[match[1]] + "," : "") + match[2];
}
for ( var key in q )
ret = (ret ? ret + "&" : "") + key + "=" + q[key];
return ret;
}
The underlying string manipulation of the browser can be horribly bad. I think it was IE6 that had a quadratic time concatenation issue. Granted, query strings aren't really going to be long enough to matter for this, but if you are for some reason parsing a lot of these at once, speed could matter.