Search and don\'t replace


/ Published in: JavaScript
Save to your folder(s)

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)


Copy this code and paste it in your HTML
  1. var q = 'foo=1&blah=a&foo=2&foo=3&blah=b'
  2.  
  3. function compress(data){
  4. var q = {}, ret = '';
  5. data.replace(/([^=&]+)=([^&]*)/g, function(m, key, value){
  6. q[key] = (q[key] ? q[key] + ',' : '') + value;
  7. });
  8. for ( var key in q )
  9. ret = (ret ? ret + '&' : '') + key + '=' + q[key];
  10. return ret;
  11. }
  12.  
  13. console.log(compress(q))

URL: http://ejohn.org/blog/search-and-dont-replace/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.