[英]How to replace string {} value to obj (key value)
I recently started programming on nodeJs.我最近开始在 nodeJs 上编程。
I have different strings and Json Object;我有不同的字符串和 Json 对象;
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).我如何自动执行此过程,因此使用 string 和 obj 我会将 string {} 值替换为 obj(键值)。
I have tried PUG but not able to parse.我试过 PUG 但无法解析。
pug.render(str, obj);
Doesn't work for me.对我不起作用。
lets see, you want to make something like templating, just like handlebars http://handlebarsjs.com/ .让我们看看,您想要制作类似模板的东西,就像把手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;
}
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)
I think you should not re-invent the wheel because the easiest solution is to use some popular node modules.我认为您不应该重新发明轮子,因为最简单的解决方案是使用一些流行的节点模块。
I suggest 'sprintf-js'.我建议'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)
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.