0

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

下面的示例字符串包含$$对变量的引用。格式为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);
4

2 回答 2

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))

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

于 2019-10-06T22:51:28.613 回答
2

你不就是在这里少了一个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/

于 2019-10-06T22:29:29.220 回答