Comments on: String.prototype.extract https://j11y.io/snippets/stringprototypeextract/ Sun, 22 Mar 2015 15:39:22 +0000 hourly 1 https://wordpress.org/?v=5.0.13 By: John.H https://j11y.io/snippets/stringprototypeextract/#comment-1117 Fri, 17 Jul 2009 09:48:11 +0000 https://j11y.io/?p=1012#comment-1117 hi,Pete, I think there is something wrong in your code, so I just modified it and it works now:

String.prototype.bindData = function (data) {
  var m,ret = this;
  while ( m = /%{s*([^}s]+)s*}/.exec(ret) ) {
    ret = ret.replace( m[0], data[m[1]] || '??' );
  }
  return ret;
};
]]>
By: Pete https://j11y.io/snippets/stringprototypeextract/#comment-1116 Tue, 14 Jul 2009 12:30:53 +0000 https://j11y.io/?p=1012#comment-1116 I did this recently, which is sort of the reverse of your extract method

String.prototype.bindData = function ( str, data ) {
  var m;
  while ( m = /%{s*([^}s]+)s*}/.exec(str) ) {
    str = str.replace( m[0], data[m[1]] || '??' );
  }
  return str;
};
 
 
// Example
 
var data = {
    'brown': 'red',
    'lazy': 'slow'
  };
 
"The quick %{brown} fox jumped over the %{lazy} dog".bindData( data );
// The quick red fox jumped over the slow dog
]]>