我有一个字符串,其中可能会出现%[{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]");它给我未捕获的SyntaxError:无效或意外的令牌错误
发布于 2016-09-26 14:42:04
在我看来,这是一个简单的基于正则表达式的字符串替换的大量代码:
var input = "{operation} + %[{cost}, 10] {?} * %[{123}, 5]";
var output = input.replace(/%\[(\{[^}]+\}), *(\d+)\]/g, "(($1*$2)/100)");
console.log(output);
发布于 2016-09-26 15:21:23
我建议你实现一个非常基本的模板引擎,或者,如果你需要很多可靠的功能,可以看看现有的一个,比如HandleBars或TwigJS。
顺便说一下,这是一个小实现:
var Template = (function() {
function TemplateEngine() {
this._re = (function(start, end) {
start = "\\" + start.split("").join("\\");
end = "\\" + end.split("").join("\\");
return new RegExp(
"(("+ start +")(.*)("+ end +"))",
"g"
);
}).apply(this, this.separators);
}
TemplateEngine.prototype.separators = ["{{", "}}"];
TemplateEngine.prototype.map = function(str, model) {
return str
.replace(this._re,
function(matches, tpl, sStart, content, sEnd) {
return Object.keys(model).reduce(function(res, variable) {
return (
res = content.replace(variable, model[variable])
);
}, "");
}
);
}
TemplateEngine.prototype.render = function(tpl, context) {
var parsed = this.map(tpl, context), result;
try {
result = eval(parsed);
} catch(e) {
result = parsed.replace(/['"`]/g, "");
}
this._re.lastIndex = 0;
return result;
};
return new TemplateEngine();
})();
// TESTS
console.log(
Template.render("{{foo * 5}}", {foo: 2})
);
console.log(
Template.render("{{foo 'World'; }}", {foo: "Hello"})
);
注意::我总是建议您使用社区信任的解决方案。
https://stackoverflow.com/questions/39696075
复制相似问题