regex - JavaScript: "Dynamic" back reference RegExp replacement -
i want make replacements this:
var txt = "some text containing $_variable1 , $_variable2 inside of 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
equal "...containing cat , hotdog ins...", way achieve i've found far this:
var replaced_txt = txt.replace(rx, function($1){return eval($1)});
and have feeling not elegant solution, no?
preferably i'd avoid eval()
i'm grateful ideas on this!
/c
you can 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 + '>'; });
Comments
Post a Comment