es6 basic 0x009: template string

0x000 overview

After the template string comes out, which good argument of single quotation mark or double quotation mark can exit the stage of history? The template string is the best!

0x001 syntax

  • Single line text

    `string text`
  • Multiline text

    `string text line 1
     string text line 2`
  • Inline expression

    `string text ${expression} string text`
  • Tag syntax (not really liked)

    tag `string text ${expression} string text`

0x002 single line text

There is no care single quotation mark or double quotation mark at all. Of course, escaping is inevitable. If you get something, you will lose it

let single=`string text, '' ""\`` // "string text, '' ""`"

0x003 multi line text, no need to worry about the code conversion of line breaking, and you can also go away

let multip=`string text line 1
 string text line 2`
 // "string text line 1
 //  string text line 2"
So we can write code like this
```
let dom=`
    I need to change lines.
    I need a new line
`
```
Although it seems to be useless for eggs

0x004 expression

This is the biggest function of template string. It has great benefits

  • More readable and less error prone string splicing

    let name='jack',age=23
    let summary=`my name is ${name}, age is ${age}`
    console.log(summary) // "my name is jack, age is 23"

    Compare the string splicing before

    let name='jack',age=23
    let summary='my name is ' + name + ', age is ' + age
    console.log(summary) // "my name is jack, age is 23"
  • Expressions can be embedded or complex, but not recommended

    let num1 = 1, num2 = 2
    `${num1} + ${num2} = ${num1 + num2}` // '1 + 2 = 3'
  • Template string nesting

    let inner=`${`${'1'}`}` // 1

0x005 label syntax

I don't like this very much

function myTag(strings, personExp, ageExp) {

  var str0 = strings[0]; // "that "
  var str1 = strings[1]; // " is a "
  var str2 = strings[2]; // " "
    
  var ageStr;
  if (ageExp > 99){
    ageStr = 'centenarian';
  } else {
    ageStr = 'youngster';
  }

  return str0 + personExp + str1 + ageStr;

}

var output = myTag`that ${ 'Mike' } is a ${ '22' }`;

console.log(output);// that Mike is a youngster

0x006 original string

The first parameter of the tag function, strings.raw, stores the original string without escape

function tag(strings) {
  console.log(strings.raw[0]);
}

tag`string text line 1 \n string text line 2`; // "string text line 1 \n string text line 2" 

The same is true with stri n g. Raw(), which is two characters.

var str = String.raw`Hi\n${2+3}!`;
// "Hi\n5!"

str.length;
// 6

str.split('').join(',');
// "H,i,\,n,5,!"

0x007 babel escape

  • Source code
let name="jack",age=23
let summary=`my name is ${name}, age is ${age}`
  • After translation

var name = "jack",
    age = 23;
var summary = "my name is " + name + ", age is " + age;

Keywords: Javascript less

Added by yorktown on Sun, 08 Dec 2019 13:54:27 +0200