A fun little JavaScript experiment with Regex.

function stringFormat(template,adata,recordStart,recordEnd) {
  var expr = template.match(/{[^}]*}/g);
  var s = template;
  var path = "", regExp;
  var result = "";
				
  for (var i=0; i<adata.length; i++) {
    var s = template;
    result += recordStart;
    for (var j=0; j<expr.length; j++) {
      path = expr[j].substring(1,expr[j].length - 1);
      path = path.replace(/\//,'.');
      regExp = new RegExp(expr[j],"g");
      s = s.replace(regExp,eval("adata[i]" + path));
    }
    result += s + recordEnd;
   }
   return result;
  }
  console.log(stringFormat("{/foo} was here {/bar}",[{foo: 'hey', bar: 'now'},{foo: 'foo', bar: 'bar'}],"<div>","</div>"));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s