用字符串中的(变量*百分比)/ 100替换%[变量,百分比]的最佳方法是什么?

时间:2016-09-26 06:33:01

标签: javascript regex

我有字符串,可能会出现%[{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:无效或意外的令牌错误

2 个答案:

答案 0 :(得分:3)

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

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

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

console.log(output);

答案 1 :(得分:0)

我建议您实现非常基础的模板引擎,或者,如果您需要许多可靠的功能,请查看现有的一个,例如HandleBars或{{ 3}}

顺便说一句,这是一个小实现:



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"})
);




注意:我建议您使用社区信任的解决方案。