How to interpolate variables in strings in JavaScript, without concatenation?

前端 未结 16 2281
长情又很酷
长情又很酷 2020-11-22 02:41

I know in PHP we can do something like this:

$hello = \"foo\";
$my_string = \"I pity the $hello\";

Output: \"I pity the foo\"<

16条回答
  •  别那么骄傲
    2020-11-22 03:18

    You can use this javascript function to do this sort of templating. No need to include an entire library.

    function createStringFromTemplate(template, variables) {
        return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
            return variables[varName];
        });
    }
    
    createStringFromTemplate(
        "I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
        {
            list_name : "this store",
            var1      : "FOO",
            var2      : "BAR",
            var3      : "BAZ"
        }
    );
    

    Output: "I would like to receive email updates from this store FOO BAR BAZ."

    Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.

提交回复
热议问题