3

I have the following that is iterating over an array of "templateOverrides". DPGlobal.template is the original template which I need to override. My issue is that I need to pass the g flag to the .replace() method on the var newTemplate = ... line. It's working insofar as I am able to dynamically iterate through and override template pieces one at a time, but the g flag is not passed. I'm mainly curious what is the most DRY method of achieving it...

for ( var i in templateOverrides ) {
    var thisOverride = templateOverrides[i];
    var origGlobalTemplate = DPGlobal[thisOverride];
    var newTemplate = DPGlobal.template.replace(origGlobalTemplate, options[thisOverride]);
    DPGlobal.template = newTemplate;
    i++;
}
Brian
  • 3,920
  • 12
  • 55
  • 100

1 Answers1

1

If you declare it via new RegExp(), you can then include the /g modifier as the second parameter to the constructor

var newTemplate = DPGlobal.template.replace(new RegExp(origGlobalTemplate,'g'), options[thisOverride]);

By the way, is templateOverrides really an Array [], or is it an object {}? If it is an Array, you ought to be using an incremental for loop rather the for-in construct, whose purpose is iterating over object properties.

for ( var i=0; i<templateOverrides.length; i++ ) {
  var thisOverride = templateOverrides[i];
  var origGlobalTemplate = DPGlobal[thisOverride];
  var newTemplate = DPGlobal.template.replace(new RegExp(origGlobalTemplate,'g'), options[thisOverride]);
  DPGlobal.template = newTemplate;
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • It is *really* an array - in which case I appreciate your help on that count as well - thanks so much! – Brian Oct 09 '12 at 15:20
  • 1
    @Brian [Here's a great explanation](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) of the difference between iteration methods and potential consequences... – Michael Berkowski Oct 09 '12 at 15:21