我想做这样的替换:
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
答案 0 :(得分:1)
你可以这样做:
var values = {
'$_variable1': 'A CAT',
'$_variable2': 'A HOTDOG'
};
var replaced_txt = txt.replace(rx, function(_, varName) {
return values[varName] ? values[varName] : '<unknown variable: ' + varName + '>';
});