5

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.

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Or as a one-liner: template.replace(/{(.+?)}/g, (m, key) => properties[key] || m)
real nice, gonna stow that away :-)
1

Here is a variation on the theme.

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)

Comments

0

I think you should not re-invent the wheel because the easiest solution is to use some popular node modules.

I suggest 'sprintf-js'.

See my sample code here,

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)

Comments

0

This is possible with single replace call.

var obj = {name : 'xyz' , age: 24};
let c_obj = {};
let wordArr = [];

const res = str.matchAll("{.*?}");

for(const match of res){

    c_obj[match[0]] =  obj[match[0].slice(1,-1)];
    wordArr.push(match[0]);

}

let new_str = str.replace(new RegExp(wordArr.join('|'),'g'), match => c_obj[match]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.