简体   繁体   English

使用全局标志将字符串文字传递为Javascript .replace()模式

[英]Passing a string literal as Javascript .replace() pattern with global flag

I have the following that is iterating over an array of "templateOverrides". 我有以下遍历“ templateOverrides”的数组。 DPGlobal.template is the original template which I need to override. DPGlobal.template是我需要覆盖的原始模板。 My issue is that I need to pass the g flag to the .replace() method on the var newTemplate = ... line. 我的问题是我需要将g标志传递给var newTemplate = ...行上的.replace()方法。 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. 只要我能够一次动态地迭代并覆盖一个模板片段,它就可以正常工作,但是不会传递g标志。 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 如果通过new RegExp()声明它,则可以将/g修饰符包括为构造函数的第二个参数

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

By the way, is templateOverrides really an Array [] , or is it an object {} ? 顺便说一句, templateOverrides 确实Array []还是对象{} 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. 如果它是Array ,则应该使用增量for循环而不是for-in构造,其目的是遍历对象属性。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM