开发者

Javascript: Reference Array Element using Regex Backreference

开发者 https://www.devze.com 2023-02-25 07:11 出处:网络
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() ex

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

精彩评论

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