Created
June 17, 2014 08:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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