Usage of the backtick character (`) in JavaScript

后端 未结 9 2143
囚心锁ツ
囚心锁ツ 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:29

    Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.

    Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.

    To escape a backtick, put a backslash before it:

    `\`` === '`'; => true
    

    Use backticks to more easily write multi-line string:

    console.log(`string text line 1
    string text line 2`);
    

    or

    console.log(`Fifteen is ${a + b} and
    not ${2 * a + b}.`);
    

    vs. vanilla JavaScript:

    console.log('string text line 1\n' +
    'string text line 2');
    

    or

    console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
    

    Escape sequences:

    • Unicode escapes started by \u, for example \u00A9
    • Unicode code point escapes indicated by \u{}, for example \u{2F804}
    • Hexadecimal escapes started by \x, for example \xA9
    • Octal literal escapes started by \ and (a) digit(s), for example \251

提交回复
热议问题