Posted By

ultranaut on 10/24/11


Tagged

javascript replace String concatenation


Versions (?)

Search and don't replace


 / Published in: JavaScript
 

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

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)

  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))

Report this snippet  

You need to login to post a comment.