Convert a string to a template string

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

    Similar to Daniel's answer (and s.meijer's gist) but more readable:

    const regex = /\${[^{]+}/g;
    
    export default function interpolate(template, variables, fallback) {
        return template.replace(regex, (match) => {
            const path = match.slice(2, -1).trim();
            return getObjPath(path, variables, fallback);
        });
    }
    
    //get the specified property or nested property of an object
    function getObjPath(path, obj, fallback = '') {
        return path.split('.').reduce((res, key) => res[key] || fallback, obj);
    }
    

    Note: This slightly improves s.meijer's original, since it won't match things like ${foo{bar} (the regex only allows non-curly brace characters inside ${ and }).


    UPDATE: I was asked for an example using this, so here you go:

    const replacements = {
        name: 'Bob',
        age: 37
    }
    
    interpolate('My name is ${name}, and I am ${age}.', replacements)
    

提交回复
热议问题