gpt4 book ai didi

javascript - 在字符串中用 (variable*percentage)/100 替换 %[variable, percentage] 的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-30 11:50:14 26 4
gpt4 key购买 nike

我有一个字符串,其中可能出现 %[{variable}, percentage] 我想将其转换为 (({variable}*percentage)/100) 并将其替换在同一位置。最好的方法是什么?

示例:{operation} + %[{cost}, 10] 应转换为 {operation} + (({cost}*10)/100)

我尝试了以下但没有成功:

function Service(){
this.percentageRegx = "\%\[(.*?)]";
this.percentageVariableRegx = "\%\[(.*?)]";
this.percentageValueRegx = "\,(.*?)]";

this.getPercentageFromFormula = function (formula) {
var data = [];

try {
do {
m = self.percentageRegx.exec(formula);
if (m) {
var variableData = self.percentageVariableRegx.exec(m[1]),
percentageData = self.percentageValueRegx.exec(m[1]);

if(variableData !== null && percentageData !== null){
data.push({
string: m[1],
variable: variableData[1],
percentage: percentageData[1]
});
}
}
} while (m);
} catch (e) {}

return data;
};

/**
* Convert percentages to formula
*/
this.replacePercentageToFormula = function (formula) {
var percentages = self.getPercentageFromFormula(formula);

angular.forEach(percentages, function (percentage) {
formula.replace(percentage.string,"(("+percentage.variable+"*"+percentage.percentage+")/100)");
});

return formula;
};
}
var service = new Service();

formula = service.replacePercentageToFormula("{operation} + %[{cost}, 10]");

它给我 Uncaught SyntaxError: Invalid or unexpected token error

最佳答案

在我看来这是一个简单的基于正则表达式的单行字符串替换代码:

var input = "{operation} + %[{cost}, 10]    {?} * %[{123}, 5]";

var output = input.replace(/%\[(\{[^}]+\}), *(\d+)\]/g, "(($1*$2)/100)");

console.log(output);

关于javascript - 在字符串中用 (variable*percentage)/100 替换 %[variable, percentage] 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39696075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com