Reputation: 119
I'm working on logic for my calculator. How do I replace all numbers with %
with an actual value in a string format?
For example:
const foo = "5%+5%+123+6%"
into
0.05 + 0.05 + 123 + 0.06
so if I used eval()
function it would calculate and the output would be:
130.43565
Upvotes: 1
Views: 253
Reputation: 20006
Use String.replaceAll
with eval
Replace %
with /100
and use eval
on the replaced string
const foo = "5%+5%+123+6%";
const replacedString = foo.replaceAll('%', '/100');
console.log(eval(replacedString));
Upvotes: 2