Skip to content

Instantly share code, notes, and snippets.

@Williammer
Created June 17, 2014 08:46
Show Gist options
  • Select an option

  • Save Williammer/c350455b11c703872baf to your computer and use it in GitHub Desktop.

Select an option

Save Williammer/c350455b11c703872baf to your computer and use it in GitHub Desktop.
jsRegExp.replaceWithFn.js - replace matched string with a callback function, with its parameters as "full match", "capturing 1st", "capturing 2nd" ... #note: using this technique with String.replace may be very useful.
function compress(source) {
var keys = {};
source.replace(
/([^=&]+)=([^&]*)/g,
function (full, key, value) {
keys[key] = (keys[key] ? keys[key] + "," : "") + value;
console.log(keys[key]);
return "";
});
var result = [];
for (var key in keys) {
result.push(key + "=" + keys[key]);
}
return result.join("&");
}
var res = compress("foo=1&foo=2&blah=a&blah=b&foo=3");
console.dir(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment