Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace string {} value to obj (key value)

I recently started programming on nodeJs.

I have different strings and Json Object;

eg :

var str = 'My name is {name} and my age is {age}.';
var obj = {name : 'xyz' , age: 24};


var str = 'I live in {city} and my phone number is {number}.';
var obj = {city: 'abc' , number : '45672778282'};

How do I automate this process, so using string and obj I will replace string {} value to obj (key value).

I have tried PUG but not able to parse.

pug.render(str, obj);

Doesn't work for me.

like image 881
Sawan Kumar Avatar asked Oct 19 '22 08:10

Sawan Kumar


1 Answers

lets see, you want to make something like templating, just like handlebars http://handlebarsjs.com/.

I will give you this example to make a simple-handlebars for you case:

function render(template, properties)
{
     var result = template;
     for (i in properties)
     {
         result = result.replace("{"+i+"}",properties[i]);
     }
     return result;
}

but this one will only change first occurence of respective properties, if you want you may use this for replace all in the whole template:

function render(template, properties)
{
     var result = template;
     for (i in properties)
     {
         var reg = new RegExp("{"+i+"}","g");
         result = result.replace(reg,properties[i]);
     }
     return result;
}
like image 97
Hans Yulian Avatar answered Nov 01 '22 12:11

Hans Yulian