Convert a string to a template string

前端 未结 19 2168
轮回少年
轮回少年 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:12

    There are many good solutions posted here, but none yet which utilizes the ES6 String.raw method. Here is my contriubution. It has an important limitation in that it will only accept properties from a passed in object, meaning no code execution in the template will work.

    function parseStringTemplate(str, obj) {
        let parts = str.split(/\$\{(?!\d)[\wæøåÆØÅ]*\}/);
        let args = str.match(/[^{\}]+(?=})/g) || [];
        let parameters = args.map(argument => obj[argument] || (obj[argument] === undefined ? "" : obj[argument]));
        return String.raw({ raw: parts }, ...parameters);
    }
    
    let template = "Hello, ${name}! Are you ${age} years old?";
    let values = { name: "John Doe", age: 18 };
    
    parseStringTemplate(template, values);
    // output: Hello, John Doe! Are you 18 years old?
    
    1. Split string into non-argument textual parts. See regex.
      parts: ["Hello, ", "! Are you ", " years old?"]
    2. Split string into property names. Empty array if match fails.
      args: ["name", "age"]
    3. Map parameters from obj by property name. Solution is limited by shallow one level mapping. Undefined values are substituted with an empty string, but other falsy values are accepted.
      parameters: ["John Doe", 18]
    4. Utilize String.raw(...) and return result.

提交回复
热议问题