如何生成一个正则表达式,用以这种方式命名的类的属性值替换标记{{name}}

How make a regular expression which replace the tags {{name}} with the value of an attribute of class named in that way

本文关键字:属性 name 方式命 替换 何生成 一个 正则表达式      更新时间:2023-09-26

我需要一个带有正则表达式的函数,用类中的属性或属性的值替换一些标记。。。我的意思是:这是我的课:

var myClass = new Object();
        myClass.id = 7;
        myClass.name = "My name";
        myClass.data = "Some text";

这是一个字符串,我想取代

var myString = "<div data-id="{{id}}"><h3>{{name}}</h3><p>{{data}}</p>"

功能必须是这样的:

function formatElement(myClass, theString){
}

如果我用类和myString调用函数,它必须返回:

"<div data-id="7"><h3>My name</h3><p>Some text<p>"

感谢所有

使用函数回调很容易:

function formatElement(myClass, theString){
    return theString.replace(/{{('w+)}}/g, function(_, s){ 
        return myClass[s];
    });
}

演示