Usage of the backtick character (`) in JavaScript

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

    You can make a template of templates too, and reach private variable.

    var a= {e:10, gy:'sfdsad'}; //global object
    
    console.log(`e is ${a.e} and gy is ${a.gy}`); 
    //e is 10 and gy is sfdsad
    
    var b = "e is ${a.e} and gy is ${a.gy}" // template string
    console.log( `${b}` );
    //e is ${a.e} and gy is ${a.gy}
    
    console.log( eval(`\`${b}\``) ); // convert template string to template
    //e is 10 and gy is sfdsad
    
    backtick( b );   // use fonction's variable
    //e is 20 and gy is fghj
    
    function backtick( temp ) {
      var a= {e:20, gy:'fghj'}; // local object
      console.log( eval(`\`${temp}\``) );
    }
    
    0 讨论(0)
  • 2020-11-22 01:22

    ECMAScript 6 comes up with a new type of string literal, using the backtick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.

    let person = {name: 'RajiniKanth', age: 68, greeting: 'Thalaivaaaa!' };
    
    let usualHtmlStr = "<p>My name is " + person.name + ",</p>\n" +
      "<p>I am " + person.age + " old</p>\n" +
      "<strong>\"" + person.greeting + "\" is what I usually say</strong>";
    
    let newHtmlStr =
     `<p>My name is ${person.name},</p>
      <p>I am ${person.age} old</p>
      <p>"${person.greeting}" is what I usually say</strong>`;
    
    console.log(usualHtmlStr);
    console.log(newHtmlStr);
    

    As you can see, we used the ` around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..} are parsed and evaluated inline immediately.

    One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:

    var Actor = {"name": "RajiniKanth"};
    
    var text =
    `Now is the time for all good men like ${Actor.name}
    to come to the aid of their
    country!`;
    console.log(text);
    // Now is the time for all good men
    // to come to the aid of their
    // country!
    

    Interpolated Expressions

    Any valid expression is allowed to appear inside ${..} in an interpolated string literal, including function calls, inline function expression calls, and even other interpolated string literals!

    function upper(s) {
      return s.toUpperCase();
    }
    var who = "reader"
    var text =
    `A very ${upper("warm")} welcome
    to all of you ${upper(`${who}s`)}!`;
    console.log(text);
    // A very WARM welcome
    // to all of you READERS!
    

    Here, the inner `${who}s` interpolated string literal was a little bit nicer convenience for us when combining the who variable with the "s" string, as opposed to who + "s". Also to keep an note is an interpolated string literal is just lexically scoped where it appears, not dynamically scoped in any way:

    function foo(str) {
      var name = "foo";
      console.log(str);
    }
    function bar() {
      var name = "bar";
      foo(`Hello from ${name}!`);
    }
    var name = "global";
    bar(); // "Hello from bar!"
    

    Using the template literal for the HTML is definitely more readable by reducing the annoyance.

    The plain old way:

    '<div class="' + className + '">' +
      '<p>' + content + '</p>' +
      '<a href="' + link + '">Let\'s go</a>'
    '</div>';
    

    With ECMAScript 6:

    `<div class="${className}">
      <p>${content}</p>
      <a href="${link}">Let's go</a>
    </div>`
    
    • Your string can span multiple lines.
    • You don't have to escape quotation characters.
    • You can avoid groupings like: '">'
    • You don't have to use the plus operator.

    Tagged Template Literals

    We can also tag a template string, when a template string is tagged, the literals and substitutions are passed to function which returns the resulting value.

    function myTaggedLiteral(strings) {
      console.log(strings);
    }
    
    myTaggedLiteral`test`; //["test"]
    
    function myTaggedLiteral(strings, value, value2) {
      console.log(strings, value, value2);
    }
    let someText = 'Neat';
    myTaggedLiteral`test ${someText} ${2 + 3}`;
    //["test", ""]
    // "Neat"
    // 5
    

    We can use the spread operator here to pass multiple values. The first argument—we called it strings—is an array of all the plain strings (the stuff between any interpolated expressions).

    We then gather up all subsequent arguments into an array called values using the ... gather/rest operator, though you could of course have left them as individual named parameters following the strings parameter like we did above (value1, value2, etc.).

    function myTaggedLiteral(strings, ...values) {
      console.log(strings);
      console.log(values);
    }
    
    let someText = 'Neat';
    myTaggedLiteral`test ${someText} ${2 + 3}`;
    //["test", ""]
    // "Neat"
    // 5
    

    The argument(s) gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal. A tagged string literal is like a processing step after the interpolations are evaluated, but before the final string value is compiled, allowing you more control over generating the string from the literal. Let's look at an example of creating reusable templates.

    const Actor = {
      name: "RajiniKanth",
      store: "Landmark"
    }
    
    const ActorTemplate = templater`<article>
      <h3>${'name'} is a Actor</h3>
      <p>You can find his movies at ${'store'}.</p>
    
    </article>`;
    
    function templater(strings, ...keys) {
      return function(data) {
        let temp = strings.slice();
        keys.forEach((key, i) => {
          temp[i] = temp[i] + data[key];
        });
        return temp.join('');
      }
    };
    
    const myTemplate = ActorTemplate(Actor);
    console.log(myTemplate);
    

    Raw Strings

    Our tag functions receive a first argument we called strings, which is an array. But there’s an additional bit of data included: the raw unprocessed versions of all the strings. You can access those raw string values using the .raw property, like this:

    function showraw(strings, ...values) {
      console.log(strings);
      console.log(strings.raw);
    }
    showraw`Hello\nWorld`;
    

    As you can see, the raw version of the string preserves the escaped \n sequence, while the processed version of the string treats it like an unescaped real new-line. ECMAScript 6 comes with a built-in function that can be used as a string literal tag: String.raw(..). It simply passes through the raw versions of the strings:

    console.log(`Hello\nWorld`);
    /* "Hello
    World" */
    
    console.log(String.raw`Hello\nWorld`);
    // "Hello\nWorld"
    
    0 讨论(0)
  • 2020-11-22 01:22

    Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.

    Features:

    • we can interpolate any kind of expression in the template literals.
    • They can be multi-line.

    Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).

    Example:

    var nameStr = `I'm "Rohit" Jindal`;
    

    To interpolate the variables or expression we can use the ${expression} notation for that.

    var name = 'Rohit Jindal';
    var text = `My name is ${name}`;
    console.log(text); // My name is Rohit Jindal
    

    Multi-line strings means that you no longer have to use \n for new lines anymore.

    Example:

    const name = 'Rohit';
    console.log(`Hello ${name}!
    How are you?`);
    

    Output:

    Hello Rohit!
    How are you?
    
    0 讨论(0)
  • 2020-11-22 01:23

    Apart from string interpolation, you can also call a function using back-tick.

    
    var sayHello = function () {
        console.log('Hello', arguments);
    }
    
    // To call this function using ``
    
    sayHello`some args`; // Check console for the output
    
    // Or
    sayHello`
        some args
    `;
    
    

    Check styled component. They use it heavily.

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

    Summary:

    Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:

    • In Template strings linebreaks are allowed and thus can be multiline. Normal string literals (declared with '' or "") are not allowed to have linebreaks.
    • We can easily interpolate variable values to the string with the ${myVariable} syntax.

    Example:

    const name = 'Willem';
    const age = 26;
    
    const story = `
      My name is: ${name}
      And I'm: ${age} years old
    `;
    
    console.log(story);

    Browser compatibility:

    Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty save to use in your production code. A more detailed list of the browser compatibilities can be found here.

    0 讨论(0)
提交回复
热议问题