Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 capturing 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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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];
});
share|improve this answer
    
Oh wow.. So simple; why didn't I think of that? Thanks! :) –  BraedenP Apr 18 '11 at 5:00
    
Because you didn't know that replace can take a function? Because it's non-trivial? You'll have to ask a new question (probably on a diffent SE site) to get an answer to that one ;-) –  Matt Ball Apr 18 '11 at 5:02
    
Hehe.. I know replace can take a function; for some reason it just didn't cross my mind. I'm just waiting until the time counts down so I can accept your answer. –  BraedenP Apr 18 '11 at 5:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.