开发者

JavaScript: "Dynamic" back reference RegExp replacement

I want to make replacements like this:

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

I want replaced_txt to equal "...containing A CAT and with A HOTDOG i开发者_Python百科ns...", but the only way to achieve this that I've found so far is this:

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

And I have a feeling this is not the most elegant solution, no?

Preferably I'd like to avoid eval()

I'm grateful for any ideas on this!

/C


You can do this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜