2017-02-25 73 views
0

我有像下面的示例模板我想用json对象值替换baby.name如何做到这一点请帮我解决这个问题。用json对象给定的字符串替换变量

var Template = 'Welcome to the world baby {{baby.name}}' 

const namelist= [{school:"hakvoz",baby: { name: 'shanker' }}]; 

帮助字符串替换需要实现这一点。 产量希望如此“欢迎来到世界宝宝鞋靴”

回答

0

您可以使用RegExp/\{{2}(.+)\}{2}/匹配"{{"捕获一个或多个字符,例如,"baby.name""}}".split()"."作为参数来获取"baby""name",利用括号表示或破坏环分配namelist阵列内获得在对象属性

var Template = 'Welcome to the world baby {{baby.name}}'; 
 

 
const namelist= [{school:"hakvoz",baby: { name: 'shanker' }}]; 
 

 
let template = Template.replace(/\{{2}(.+)\}{2}/, function(match, p1) { 
 
    let [prop, key] = p1.split("."); 
 
    return namelist[0][prop][key]; 
 
}); 
 

 
document.querySelector("pre").textContent = template;
<pre></pre>

+0

类型错误:无法读取的未定义的属性“婴儿”在此行中返回名称列表[0] [丙] [键]。 – user7620655

0

您可能需要查看template literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

string text ${expression} string text

所以你的情况变得

var Template = 'Welcome to the world baby ${namelist[0].baby.name}'