Usage of the backtick character (`) in JavaScript

后端 未结 9 2153
囚心锁ツ
囚心锁ツ 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
    0 讨论(0)
  • 2020-11-22 01:34

    The good part is we can make basic maths directly:

    let nuts = 7
    
    more.innerHTML = `
    
    <h2>You collected ${nuts} nuts so far!
    
    <hr>
    
    Double it, get ${nuts + nuts} nuts!!
    
    `
    <div id="more"></div>

    It became really useful in a factory function:

    function nuts(it){
      return `
        You have ${it} nuts! <br>
        Cosinus of your nuts: ${Math.cos(it)} <br>
        Triple nuts: ${3 * it} <br>
        Your nuts encoded in BASE64:<br> ${btoa(it)}
      `
    }
    
    nut.oninput = (function(){
      out.innerHTML = nuts(nut.value)
    })
    <h3>NUTS CALCULATOR
    <input type="number" id="nut">
    
    <div id="out"></div>

    0 讨论(0)
  • 2020-11-22 01:35

    It's a pretty useful functionality, for example here is a Node.js code snippet to test the set up of a 3 second timing function.

    const waitTime = 3000;
    console.log(`setting a ${waitTime/1000} second delay`);
    

    Explanation

    1. Declare wait time as 3000
    2. Using the backtick you can embed the result of the calculation of 'wait time' divided by 1000 in the same line with your chosen text.
    3. Further calling a timer function using the 'waitTime' constant will result in a 3 second delay, as calculated in the console.log argument.
    0 讨论(0)
提交回复
热议问题