Javascript string replace with calculations

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-05-16T11:03:55Z Indexed on 2010/05/16 11:10 UTC
Read the original article Hit count: 272

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:

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

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:

string = "Something [X], something [Y]. Something [(X+Y^2)/5X]";

And for the [_] parts to be understood as expressions to be resolved before substituting back into the string.

Thanks for your help.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about string