开发者

regular expression in Crockford's String.supplant

I need to create a function like Douglas Crockford's 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;
        });
    };
}

what it does is:

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>

i need, for a project for my tags to be different: instead of {tagname}, i need it to be [ns:tagname]

does anyone here have enough knowledge of regular expres开发者_JAVA百科sions to help me out?

thank you very much


The following works:

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

Do note, that the brackets are escaped (e.g., [] becomes \[\]) since they have a special meaning in regular expressions.

Example:

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>"


The regexp would need to be changed.

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>

New regexp: \[ns:([^:\[\]]*)].

First a [ (special character while it is the literal [ here, so needs to be escaped).

Then ns:.

After that any amount of any characters that does not contain a [, ] or ::

(     // start group
[^    // none of following
:\[\] // : [ ]
]*    // any amount
)     // end group

Lastly a ].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜