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

前端 未结 16 2518
长情又很酷
长情又很酷 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:11

    I would use the back-tick ``.

    let name1 = 'Geoffrey';
    let msg1 = `Hello ${name1}`;
    console.log(msg1); // 'Hello Geoffrey'
    

    But if you don't know name1 when you create msg1.

    For exemple if msg1 came from an API.

    You can use :

    let name2 = 'Geoffrey';
    let msg2 = 'Hello ${name2}';
    console.log(msg2); // 'Hello ${name2}'
    
    const regexp = /\${([^{]+)}/g;
    let result = msg2.replace(regexp, function(ignore, key){
        return eval(key);
    });
    console.log(result); // 'Hello Geoffrey'
    

    It will replace ${name2} with his value.

提交回复
热议问题