Template literals with nested backticks(`) in ES6

前端 未结 8 978
离开以前
离开以前 2020-12-03 04:23

How can I write a template literal in ECMAScript 6 that will contain backticks(`) in and by itself, (i.e. nested backticks)?

For example:

var qu         


        
8条回答
  •  眼角桃花
    2020-12-03 04:58

    ES6 has new features:

    • Template literals
    • Tagged template literals (tagged templates)

    Which make working with strings easier. You wrap your text in `backticks`.

    With this we can:

    1. Interpolate variables

      let foo = "abc";
      
      console.log(`Welcome ${foo}`); // Welcome abc
      
    2. Interpolate any kind of expression

      console.log(`2+3 = ${2+3}`) // 2+3 = 5
      
    3. Declare strings with both ' and " quotation marks without having to escape anything.

      let foo = `foo is 'bar', "bar" is foo`
      
      console.log(foo); // "foo is 'bar', "bar" is foo"
      
    4. Cleaner syntax for multi-line string

      let text = `foo is bar
      
      bar is foo`
      
      console.log(text);
      
      //"foo is bar
      
      //bar is foo"
      
    5. Tagged templates, we can pass template literals to a function, here is how:

      let person = 'Mike';
      let age = 28;
      
      let output = myTag `that ${ person } is ${ age }`;
      
      function myTag(strings, personExp, ageExp) {
      
          // strings[0] gets value "that "
          // strings[1] gets value " is "
          // personExp  gets value " Mike "
          // ageStr     gets value "28"
      
          return strings[0] + personExp + strings[1] + ageExp;
      }
      
      console.log(output);
      
      // that Mike is 28
      
    6. String.raw, we can get the raw form, here is the example:

      let text = String.raw `The "\n" newline won't result in a new line.'
      console.log(text);
      // The "\n" newline won't result in a new line.
      

提交回复
热议问题