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];
});
精彩评论