[英]recursive replace with javascript regex
I have a string: pow(pow(487,2)+873,2) that I generate from a calculator I am creating.我有一个字符串: pow(pow(487,2)+873,2) 我从我正在创建的计算器生成的。 I want to trans-pile it to ((487^2) + 873)^2.我想将其转换为 ((487^2) + 873)^2。
I had no problem with trans-piling pow(487,2) to 487^2 using我使用将 pow(487,2) 转换为 487^2 没有问题
var string = `pow(487,2)`;
console.log(string.replace(/pow\((.*?),(.*?)\)/g,'$1^$2'));
The problem is that I don't know how to handle it recursively with pow(pow(487,2)+873,2) to become ((487^2) + 873)^2.问题是我不知道如何用 pow(pow(487,2)+873,2) 递归处理它变成 ((487^2) + 873)^2。 Please help.请帮忙。
you can write recursive function to achieve like this您可以编写递归 function 来实现这样的
var string = `pow(pow(487,2)+873,2)`;
var numberOfOccurance = string.match(/pow/g).length;
const makeTranspile=(str,nooc)=>{
const newStr=str.replace(/pow\((.*?),(.*?)\)/g,'($1)^$2');
if(nooc>1)
{
return makeTranspile(newStr,nooc-1)
}
return newStr
}
const finalString=makeTranspile(string,numberOfOccurance);
console.log(finalString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.