【问题标题】:Variable substitution within a string字符串中的变量替换
【发布时间】:2020-02-04 06:49:00
【问题描述】:

我正在尝试编写一些非常可重用的代码,这些代码将在字符串中查找并执行变量替换。

下面的示例字符串包含对变量的$$ 引用。格式为varname.key。

我希望subText() 函数可重用。我遇到的问题是repvars 他们自己可能需要替换。代码还没有完成替换示例文本,我要求它通过调用相同的函数来替换 repvars.cr。这似乎通过它关闭。我这么说是因为如果我在作品中分开做。

var exampleText = "A string of unlimited length with various variable substitutions included $$repvars.cr$$";
    var repvars = {
        cr: 'Copyright for this is $$repvars.year$$',
        year: '2019'
    }

function subText(text) {
    var subVars = findSubs(text);
    return makeSubs(text, subVars);
}

function findSubs(theText) {
    var subarr = [];
    while (theText.indexOf('$$') > -1) {
        theText = theText.substring(theText.indexOf('$$') + 2);
        subarr.push(theText.substring(0, theText.indexOf('$$')));
        theText = theText.substring(theText.indexOf('$$') + 2);
    }
    return subarr;
}

function makeSubs(text, subs) {
    for (var s = 0; s < subs.length; s++) {
        var subst = getSubVal(subs[s]);
        text = text.split("$$" + subs[s] + "$$").join(subst);
    }
    return text;
}

function getSubVal(subvar) {
    var subspl = subvar.split('.');
    switch (subspl[0]) {
        default:
            return processRepVar(subspl[1]);
    }
}

function processRepVar(rvName) {
    var data = getRepVarData(rvName);
 if(data.indexOf('$$') > -1) {
   subText(data);
 } else {
  return data; 
 }
}

function getRepVars() {
    return repvars;
}

function getRepVarData(key) {
    return getRepVars()[key];
}

subText(exampleText);

【问题讨论】:

    标签: javascript str-replace variable-substitution


    【解决方案1】:

    你不只是在这里缺少return吗?

    function processRepVar(rvName) {
        var data = getRepVarData(rvName);
     if(data.indexOf('$$') > -1) {
       subText(data);
     } else {
      return data; 
     }
    }
    

    将subText(data) 更改为return subText(data); 使您的代码对我有用。

    工作 jsfiddle:https://jsfiddle.net/uzxno754/

    【讨论】:

      【解决方案2】:

      你试过正则表达式吗?

      function replace(str, data) {
        let re = /\$\$(\w+)\$\$/g;
        
        while (re.test(str))
          str = str.replace(re, (_, w) => data[w]);
          
        return str;
      }
      
      //
      
      var exampleText = "A string with variables $$cr$$";
      
      var repvars = {
        cr: 'Copyright for this is $$year$$',
        year: '2019'
      }
      
      console.log(replace(exampleText, repvars))

      基本上,这会重复替换字符串中的 $$...$$ 内容,直到没有更多内容为止。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-16
        • 1970-01-01
        • 2020-07-09
        • 2020-03-30
        • 1970-01-01
        • 2011-08-18
        • 1970-01-01
        相关资源
        最近更新 更多