首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在字符串中用(variable*percentage)/100替换%[variable,percentage]的最佳方法是什么?

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

Stack Overflow用户
提问于 2016-09-26 14:33:01
回答 2查看 155关注 0票数 1

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

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

我试着追随,但没有起作用:

代码语言:javascript
复制
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:无效或意外的令牌错误

EN

回答 2

Stack Overflow用户

发布于 2016-09-26 14:42:04

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

代码语言:javascript
复制
var input = "{operation} + %[{cost}, 10]    {?} * %[{123}, 5]";

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

console.log(output);

票数 3
EN

Stack Overflow用户

发布于 2016-09-26 15:21:23

我建议你实现一个非常基本的模板引擎,或者,如果你需要很多可靠的功能,可以看看现有的一个,比如HandleBarsTwigJS

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

代码语言:javascript
复制
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"})
);

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39696075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档