简体   繁体   中英

Variable substitution within a string

I'm trying to come up with some very reusable code that will look up and perform variable substitutions within a string.

The example string below contains a $$ reference to a variable. Format is varname.key .

I want the subText() function to be reusable. The issue I'm having is repvars themselves can require substitution. The code hasn't finished substituting the example text and I'm asking it to substitute the repvars.cr by calling the same function. This seems to through it off. I'm saying that because if I do it separately in works.

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

Aren't you just missing a return here?

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

Changing subText(data) to return subText(data); makes your code work for me.

Working jsfiddle: https://jsfiddle.net/uzxno754/

Have you tried regular expressions for this?

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

Basically, this repeatedly replaces $$...$$ things in a string until there are no more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM