JSFiddle - React, Tailwind, and code Playground

by Andreas Renberg

JavaScript

function math(match, leftDigit, operator, rightDigit, offset, string) {
	var L = parseFloat(leftDigit)
	var R = parseFloat(rightDigit)
	switch (operator)
	{
	    case '*': return L*R;
	    case '/': return L/R;
	    case '+': return L+R;
	    case '-': return L-R;
	}
};

str = prompt("Enter some math:", "-2 + 6 / 2 * 8 - 1 / 2.5 - 18").replace(/ /g, "");
var mathRegex = /(\-?\d+\.?\d*)([\*\/\+\-])(\-?\d+\.?\d*)/;
while(mathRegex.test(str)) {
	str = str.replace(mathRegex, math);
}
alert(str)