title: Javascript string replace with calculations
body: <p>Is there a way to resolve mathematical expressions in strings in javascript? For example, suppose I want to produce the string "Tom has 2 apples, Lucy has 3 apples. Together they have 5 apples" but I want to be able to substitute in the variables. I can do this with a string replacement:</p>
  
  <pre><code>string = "Tom has X apples, Lucy has Y apples. Together they have Z apples";
  string2 = string.replace(/X/, '2').replace(/Y/, '3').replace(/Z/, '5');
  </code></pre>
  
  <p>However, it would be better if, instead of having a variable Z, I could use X+Y. Now, I could also do a string replace for X+Y and replace it with the correct value, but that would become messy when trying to deal with all the possible in-string calculations I might want to do. I suppose I'm looking for a way to achieve this:</p>
  
  <pre><code>string = "Something [X], something [Y]. Something [(X+Y^2)/(5*X)]";
  </code></pre>
  
  <p>And for the [___] parts to be understood as expressions to be resolved before substituting back into the string.</p>
  
  <p>Thanks for your help.  </p>