简体   繁体   中英

How to replace characters recursively within a string

I have a mathematical expression that does exponentials (eg 2 Raised to the power of 2) which I normally pass to the JavaScript eval function. An example of my string expression is 2^2^2. Now, JavaScript doesn't have an exponential operator so in the current example the operator you see between the operands is a bitwise operator in JavaScript.

What I try to do is to replace the string that matches the pattern d1 ^ d2 with the value returned from Math.pow (d1, d2). Now, it does this successfully for the first occurence but doesn't do it for other occurrences. Below is my code:

var str = '2^2^2';
var regex = /(\d+)\^(\d+)/g;

str = str.replace(c, function(match, $1, $2) {
    console.log(match + '---' + $1 + '---' + $2);
    return Math.pow($1,$2);
});
console.log(str);

eval(str);

Anytime I log the ouput of str it gives 4^2 instead of 16 and so I always get the wrong answer after the eval function actions. Please does anyone have any idea how I can go about solving this problem.

You could use a recursive function that stops when no other token was matched. For example:

 var str = '2^2^2'; var regex = /(\\d+)\\^(\\d+)/g; function recursive(str) { var matched = false; str = str.replace(regex, function(match, $1, $2) { if (match) { matched = true; } return Math.pow($1, $2); }); if (matched) { str = recursive(str); } return str; } var result = recursive(str); console.log(result); 
 <script src="http://gh-canon.github.io/stack-snippet-console/console.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