Javascript Crockford'中的正则表达式;s String.replacement

Javascript Crockford'中的正则表达式;s String.replacement,javascript,regex,Javascript,Regex,我需要创建一个类似Douglas Crockford的String.replacement的函数: if (typeof String.prototype.supplant !== 'function') { String.prototype.supplant = function (o) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = o[b];

我需要创建一个类似Douglas Crockford的String.replacement的函数:

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;
        });
    };
}
它所做的是:

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>
var html='{title}{time}{content}

'; var对象={title:“我的标题”,时间:“12h00m”,内容:“blablabla”} replacemented=html.replacement(对象); //替代申报表: //我的标题12h00mblabla

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

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

以下作品:

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;
        });
    };
}
请注意,括号是转义的(例如,
[]
变为
\[\]
),因为它们在正则表达式中有特殊含义

例如:

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>"
var html='[ns:title][ns:time][ns:content]

'; var对象={title:“我的标题”,时间:“12h00m”,内容:“blablabla”} replacemented=html.replacement(对象); //“我的标题12h00mblabla


需要更改regexp

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;
        });
    };
}

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);
//supplanted returns:
//<div>my title<h3>12h00m</h3><p>blablabla</p></div>

最后a
]

谢谢,我不得不接受jensgram,因为她比我快了2分钟。但是谢谢你,really@Andr阿尔çada Padez不客气。顺便说一句:我是一个男性-名字是延斯克。我不是:)@AndréAlçada Padez不,我把评论弄混了。我在你对pimvdb的评论中提到“…因为她只有2分钟…”。我有一个简单的问题,a,b在内部函数中是什么?它们来自哪里?@zer0c00l
a
b
只是我在匿名替换函数中用于第一个和第二个参数的参数名。有关完整列表,请访问。
(     // start group
[^    // none of following
:\[\] // : [ ]
]*    // any amount
)     // end group