如何将字符串{}值替换为obj(键值) [英] How to replace string {} value to obj (key value)

查看:122
本文介绍了如何将字符串{}值替换为obj(键值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始在nodeJs上编程.

I recently started programming on nodeJs.

我有不同的字符串和Json对象;

I have different strings and Json Object;

例如:

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'};

该如何自动执行此过程,因此我将使用字符串和obj将字符串{}值替换为obj(键值).

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

我尝试了PUG,但无法解析.

I have tried PUG but not able to parse.

pug.render(str, obj);

对我不起作用.

推荐答案

让我们看到,您想要制作类似于模板的东西,就像把手 http://handlebarsjs.com/.

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

这篇关于如何将字符串{}值替换为obj(键值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆