简体   繁体   中英

** operator not supported in IE11. How to replace it with Math.pow using code?

I have this example formula:

((97000 * ((5.50/100)/12)) / (1 - ((1 + ((5.50/100)/12))**(-1 * 120))))

The problem is that this code is not working correctly in IE11. I have tried this method to replace each ** with Math.pow , but I cannot get it to work correctly:

 function detectAndFixTrivialPow(expressionString) { var pattern = /(\\w+)\\*\\*(\\w+)/i; var fixed = expressionString.replace(pattern, 'Math.pow($1,$2)'); return fixed; } var expr = "((97000 * ((5.50/100)/12)) / (1 - ((1 + ((5.50/100)/12))**(-1 * 120))))"; var expr2 = detectAndFixTrivialPow(expr); console.log(expr); console.log(expr2); // no change...

Trying this with a regular expression is going to be tough. Instead use a transpiler or at least an ECMAScript parser.

Here is an example how it can be done with the esprima parser. This API produces an AST tree. The code below looks for the ** operator in that tree and collects the offsets where the input string should change. Then these offsets are sorted in descending order to apply them in the right order to the input string.

Note that this code does not attempt to save any parentheses. Those in the input are retained, and an extra pair is added for each of the Math.pow calls.

 function convert(input) { let modifs = []; function recur(ast) { if (Object(ast) !== ast) return; // not an object if (ast.type === "BinaryExpression" && ast.operator == "**") { modifs.push( [ast.range[0], 0, "Math.pow("], [input.indexOf("**", ast.left.range[1]), 2, ","], [ast.range[1], 0, ")"] ); } Object.values(ast).forEach(recur); } recur(esprima.parse(expr, { range: true })); modifs.sort(([a], [b]) => b - a); let output = [...input]; for (let params of modifs) output.splice(...params); return output.join(""); } // Demo let expr = "((97000 * ((5.50/100)/12)) / (1 - ((1 + ((5.50/100)/12))**(-1 * 120))))" let result = convert(expr); console.log(result);
 <script src="https://cdn.jsdelivr.net/npm/esprima@4.0.1/dist/esprima.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM