Convert a string to a template string

前端 未结 19 2148
轮回少年
轮回少年 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条回答
  • 2020-11-22 09:32

    I liked s.meijer's answer and wrote my own version based on his:

    function parseTemplate(template, map, fallback) {
        return template.replace(/\$\{[^}]+\}/g, (match) => 
            match
                .slice(2, -1)
                .trim()
                .split(".")
                .reduce(
                    (searchObject, key) => searchObject[key] || fallback || match,
                    map
                )
        );
    }
    
    0 讨论(0)
提交回复
热议问题