我想这样替换:

var txt = "Some text containing $_variable1 and with $_variable2 inside of it as well.";
var rx = /(\$_[a-z]+)/g

var $_variable1 = "A CAT";
var $_variable2 = "A HOTDOG";

var replaced_txt = txt.replace(rx, $1);


我希望replaced_txt等于“ ...包含CAT和HOTDOG ins ...”,但是到目前为止,我发现的唯一实现方法是:

var replaced_txt = txt.replace(rx, function($1){return eval($1)});


而且我觉得这不是最优雅的解决方案,不是吗?

最好我想避免eval()

我对此有任何想法表示感谢!

/C

最佳答案

你可以这样做:

var values = {
  '$_variable1': 'A CAT',
  '$_variable2': 'A HOTDOG'
};
var replaced_txt = txt.replace(rx, function(_, varName) {
  return values[varName] ? values[varName] : '<unknown variable: ' + varName + '>';
});

关于javascript - JavaScript:“动态”反向引用RegExp替换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4327053/

10-10 10:37