Using Javascript and RegEx, how I can start with something like this…
((5 dogs + 2 cats) * $3.00 per animal) + $20 flat fee
…and end up with just the math operators (allowing for both x and * for multiplication), dollar signs, decimal points, spaces and numbers…
(5 + 2) * $3.00) + $20
Ideally, there would be two levels of nesting max; but if that’s not possible, one level would also be useful.
>Solution :
You could use a string replace using a regular expression matching only symbols different from the allowed characters: +-*/[0-9]$() to be replaced with empty string.
Here’s a demo:
const formula = "((5 dogs + 2 cats) * $3.00 per animal) + $20 flat fee";
const result = formula.replace(/[^-+*\/()\d$]/img, "");
console.log(result);