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++;
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.