Reputation: 909
I have string where there may be occurrence of %[{variable}, percentage]
which i want to convert to (({variable}*percentage)/100)
and replace it at same location. What is best way to do it?
Example: {operation} + %[{cost}, 10]
should be converted to {operation} + (({cost}*10)/100)
I tried following but it didn't work:
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]");
It giving me Uncaught SyntaxError: Invalid or unexpected token error
Upvotes: 1
Views: 528
Reputation: 14189
I suggest you to implement a very very basilar template engine, or, if you need for many and solid features, have a look at one existing such as HandleBars, or TwigJS.
By the way, this is a little implementation:
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"})
);
NOTE: I always suggest you to use a community-trusted solution.
Upvotes: 0
Reputation: 150070
That's a lot of code for what seems to me like a simple one-line regex-based string replacement:
var input = "{operation} + %[{cost}, 10] {?} * %[{123}, 5]";
var output = input.replace(/%\[(\{[^}]+\}), *(\d+)\]/g, "(($1*$2)/100)");
console.log(output);
Upvotes: 3