按名称将文本替换为 JavaScript 属性的内容

Replace text with content of a JavaScript property by name

本文关键字:属性 JavaScript 文本替换      更新时间:2023-09-26

我有这个正则表达式:

/'{([a-zA-Z'.]*)'

我想用它来替换一些这样的文本:

{identifier}

带值 带有括号值名称的对象属性。在这种情况下,它将是 object.identifier .像这样:

html.replace(/'{([a-zA-Z'.]*)'}/g, object.$1);

感谢您的快速共鸣,这是最终代码

html = html.replace(/'{([a-zA-Z'.]*)'}/g, $.proxy(function (match, contents, offset, s) {
    return objx.get(this.response[object.attr("data-index")],contents);
},this));

您可以指定.replace的回调:

html.replace(/{([a-zA-Z.]*)}/g, function(x, a) {
    return object[a];
});