1

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 ins...", 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

1 Answer 1

1

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 + '>';
});
Sign up to request clarification or add additional context in comments.

2 Comments

Seems right. I'm pretty sure values[var] || 'default' would be neater here, and var may not be the best variable name (does it work?)
... and yes you could do the || thing but I was trying to be clear for pedagogical reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.