Convert a string to a template string

前端 未结 19 2526
轮回少年
轮回少年 2020-11-22 08:30

Is it possible to create a template string as a usual string

let a=\"b:${b}\";

an then convert it into a template string

le         


        
19条回答
  •  猫巷女王i
    2020-11-22 09:20

    Since we're reinventing the wheel on something that would be a lovely feature in javascript.

    I use eval(), which is not secure, but javascript is not secure. I readily admit that I'm not excellent with javascript, but I had a need, and I needed an answer so I made one.

    I chose to stylize my variables with an @ rather than an $, particularly because I want to use the multiline feature of literals without evaluating til it's ready. So variable syntax is @{OptionalObject.OptionalObjectN.VARIABLE_NAME}

    I am no javascript expert, so I'd gladly take advice on improvement but...

    var prsLiteral, prsRegex = /\@\{(.*?)(?!\@\{)\}/g
    for(i = 0; i < myResultSet.length; i++) {
        prsLiteral = rt.replace(prsRegex,function (match,varname) {
            return eval(varname + "[" + i + "]");
            // you could instead use return eval(varname) if you're not looping.
        })
        console.log(prsLiteral);
    }
    

    A very simple implementation follows

    myResultSet = {totalrecords: 2,
    Name: ["Bob", "Stephanie"],
    Age: [37,22]};
    
    rt = `My name is @{myResultSet.Name}, and I am @{myResultSet.Age}.`
    
    var prsLiteral, prsRegex = /\@\{(.*?)(?!\@\{)\}/g
    for(i = 0; i < myResultSet.totalrecords; i++) {
        prsLiteral = rt.replace(prsRegex,function (match,varname) {
            return eval(varname + "[" + i + "]");
            // you could instead use return eval(varname) if you're not looping.
        })
        console.log(prsLiteral);
    }

    In my actual implementation, I choose to use @{{variable}}. One more set of braces. Absurdly unlikely to encounter that unexpectedly. The regex for that would look like /\@\{\{(.*?)(?!\@\{\{)\}\}/g

    To make that easier to read

    \@\{\{    # opening sequence, @{{ literally.
    (.*?)     # capturing the variable name
              # ^ captures only until it reaches the closing sequence
    (?!       # negative lookahead, making sure the following
              # ^ pattern is not found ahead of the current character
      \@\{\{  # same as opening sequence, if you change that, change this
    )
    \}\}      # closing sequence.
    

    If you're not experienced with regex, a pretty safe rule is to escape every non-alphanumeric character, and don't ever needlessly escape letters as many escaped letters have special meaning to virtually all flavors of regex.

提交回复
热议问题