user359135
user359135

Reputation:

Javascript: something like string.format with property names

I wanted to make a method that i could pass a recordset (could just as easily be an general object) with format string to replace values by name. I found this other answer on SO that almost did it: https://stackoverflow.com/a/2534828/359135

function format(str, obj) {
    return str.replace(/\{\s*([^}\s]+)\s*\}/g, function(m, p1, offset, string) {
        return obj[p1]
    })
}

but it does not quite work (i don't think): http://jsfiddle.net/9Jpkv/24/

NOTE: my recordset version would just be:

function format(str, rs) {
    return str.replace(/\{\s*([^}\s]+)\s*\}/g, function(m, p1, offset, string) {
        return rs(p1); //use recordset names accessors instead of object properties
    })
}

I would like to be able to do this without iterating over the properties of the object (or columns of the recordset) like the above code almost manages to do. instead it loks for items between curly braces and tries to find them in teh object properties (or record set columns)

Or actually I am a idiot and the above actually does work!: http://jsfiddle.net/9Jpkv/26/

I was not passing passing in an object!

Upvotes: 1

Views: 2750

Answers (2)

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7169

function template(str, data) {
  data = data || {};
  Object.keys(data).forEach(function(key) {
   str = str.replace(new RegExp('{{' + key + '}}', 'g'), data[key]);
  });
  return str;
}

Like this? -- it replace all {{name}} to corresponded values from data param

template('<div>{{name1}}</div> <span>{{name2}}</span>', { name1: 'value1', name2: 'value2' })

http://jsbin.com/kefazajude/edit?js,console

or

function template(str, data) {
  data = data || {};

  str.match(/{{(.+?)}}/g).forEach(function(key) {
   str = str.replace(key, data[key.replace('{{','').replace('}}', '')]);
  });
  return str;
}

http://jsbin.com/baxuyateme/edit?js,console

for curly bracket

function template(str, data) {
  data = data || {};

  str.match(/{(.+?)}/g).forEach(function(key) {
   str = str.replace(key, data[key.replace('{','').replace('}', '')]);
  });
  return str;
}

http://jsbin.com/tumobohelo/edit?js,console

Upvotes: 3

codeaholicguy
codeaholicguy

Reputation: 1691

String.format = function() {
    var theString = arguments[0];

    for (var i = 1; i < arguments.length; i++) {
        var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
        theString = theString.replace(regEx, arguments[i]);
    }

    return theString;
}

Use:

var string = String.format('{0}-{1}-{2}', string1, string2, string3);

You should take a look at JavaScript equivalent to printf/string.format, this might be helpful.

Upvotes: 2

Related Questions