Posted By

Pjotor on 04/30/10


Tagged

replace pattern String


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

VaiT


Pattern replace String prototype


 / Published in: JavaScript
 

Quick and dirty pattern string replacer. Usage: "my {color} {fruit}".prep({ color: "red", favourite: { fruit: "apple" } }) --> "my red apple"

  1. String.prototype.prep = function(d){
  2. var s = this;
  3. var keys = (s.match(/\${(..*?)}/g) || []);
  4. var getVal = function (path) {
  5. return path.split('.').reduce(function(a, b){ return a[b] || '${'+path+'}' }, d);
  6. }
  7. keys.forEach( function (i) {
  8. s = s.replace(i, function ($1) { return getVal($1.substr(2,$1.length-3)); });
  9. });
  10. return s;
  11. }

Report this snippet  

You need to login to post a comment.