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

I recently started programming on nodeJs.

I have different lines 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 can I automate this process, so using string and obj, I will replace the string {} value with obj (key value).

I tried PUG but could not make out.

pug.render(str, obj);

Not working for me.

+4
source share
3 answers

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

I will give you this example to create a simple case for you:

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

, , :

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;
}
+2

.

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

var render = function (str, obj) {
    return Object.keys(obj).reduce((p,c) => {
        return p.split("{" + c + "}").join(obj[c])
    }, str)
}

render(str, obj)
+1

I think you should not reinvent the wheel, because the simplest solution is to use some popular node modules.

I suggest "sprintf-js".

See my sample code,

const sprintfJs = require('sprintf-js')

const template = 'hello %(name)s today is %(day)s'
const data = {
  name: 'xxxx',
  day: 'Tuesday'
}

const formattedString = sprintfJs.sprintf(template, data)
console.log(formattedString)
0
source

All Articles