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

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

    You can take advantage of Template Literals and use this syntax:

    `String text ${expression}`
    

    Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.

    This feature has been introduced in ES2015 (ES6).

    Example

    var a = 5;
    var b = 10;
    console.log(`Fifteen is ${a + b}.`);
    // "Fifteen is 15.
    

    How neat is that?

    Bonus:

    It also allows for multi-line strings in javascript without escaping, which is great for templates:

    return `
        
    ...
    `;

    Browser support:

    As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.


    Side note:

    Starting from IE8+ you can use basic string formatting inside console.log:

    console.log('%s is %d.', 'Fifteen', 15);
    // Fifteen is 15.
    

提交回复
热议问题