Crockford的String.supplant中的正则表达式

And*_*dez 3 javascript regex

我需要创建一个像Douglas Crockford的String.supplant这样的函数:

if (typeof String.prototype.supplant !== 'function') {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g, function (a, b) {
            var r = o[b];
            return typeof r === 'string' ? r : a;
        });
    };
}
Run Code Online (Sandbox Code Playgroud)

它的作用是:

var html = '<div>{title}<h3>{time}</h3><p>{content}</p></div>';
var object = {title: "my title", time: "12h00m", content:"blablabla"}
supplanted = html.supplant(object);
//supplanted returns:
//<div>my title<h3>12h00m</h3><p>blablabla</p></div>
Run Code Online (Sandbox Code Playgroud)

我需要,对于我的标签的项目是不同的:而不是{tagname},我需要它[ns:tagname]

这里有没有人有足够的正则表达式知识来帮助我?
非常感谢你

jen*_*ram 6

以下作品:

if (typeof String.prototype.supplant !== 'function') {
    String.prototype.supplant = function (o) {
        return this.replace(/\[ns:([^\[\]]*)\]/g, function (a, b) {
            var r = o[b];
            return typeof r === 'string' ? r : a;
        });
    };
}
Run Code Online (Sandbox Code Playgroud)

请注意,括号是转义的(例如,[]变为\[\]),因为它们在正则表达式中具有特殊含义.

例:

var html = '<div>[ns:title]<h3>[ns:time]</h3><p>[ns:content]</p></div>';
var object = {title: "my title", time: "12h00m", content:"blablabla"}
supplanted = html.supplant(object);
// "<div>my title<h3>12h00m</h3><p>blablabla</p></div>"
Run Code Online (Sandbox Code Playgroud)