Usage of the backtick character (`) in JavaScript

后端 未结 9 2271
囚心锁ツ
囚心锁ツ 2020-11-22 00:51

In JavaScript, a backtick seems to work the same as a single quote. For instance, I can use a backtick to define a string like this:

var s         


        
9条回答
  •  独厮守ぢ
    2020-11-22 01:17

    This is a feature called template literals.

    They were called "template strings" in prior editions of the ECMAScript 2015 specification.

    Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.

    • Examples: http://tc39wiki.calculist.org/es6/template-strings/
    • Official specification: ECMAScript 2015 Language Specification, 12.2.9 Template Literal Lexical Components (a bit dry)

    Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:

    var a = 123, str = `---
       a is: ${a}
    ---`;
    console.log(str);
    

    Output:

    ---
       a is: 123
    ---
    

    What is more important, they can contain not just a variable name, but any JavaScript expression:

    var a = 3, b = 3.1415;
    
    console.log(`PI is nearly ${Math.max(a, b)}`);
    

提交回复
热议问题