开发者

Javascript: Reference Array Element using Regex Backreference

Basically, I'm trying to replace parts of a string using elements from an associative array. However, I need to grab elements based on backreferences generated from capturing groups in a replace() expression.

Using the first captur开发者_如何学Going group, I created this code, which doesn't work:

content = content.replace(/%(\w+)%/g,this.vars["$1"]);

(The regex works fine... I just can't get it to grab the array element.)

How would I go about implementing something like this?


String.replace can take a function as the second argument.

var that = this,
    re = /%(\w+)%/g;

content = content.replace(re, function (str, p1)
{
    return that.vars[p1];
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜