JSFiddle - React, Tailwind, and code Playground
by amasad
JavaScript
function clean(x){
var i = x.indexOf('^');
while (!!~i){
if (x[i-1] === ')'){
x = x.replace(/(\([^\)]+\))\^/,'Math.pow($1,^');
}else if(x[i-1] !== ')' && x[i-1] !== ',' ){
x =x.replace(/([A-Za-z0-9\.]+)\^/, 'Math.pow($1,^');
}else if (x[i+1] === '('){
x = x.replace(/\^(\([^\)]+\))/, '$1)');
}else {
x =x.replace(/\^([A-Za-z0-9\.]+)/, '$1)');
}
i = x.indexOf('^');
}
return x;
}
document.write(clean('(x-1)^2'))