Hướng dẫn backtick inside backtick javascript

I want to write backtick inside backtick. [es6]

How do you create backtick in backtick ?

const apple = 'apple';
const grape = 'grape';
const money1 = 2000;
const money2 = 1000;


// before
console.log[`${apple} = ${grape === 'grape' ? '[' + money1 + ']' : '[' + money2 + ']'`;

// after  
  String.raw[{ raw: strings }, ...values];
console.log[identity`Hi\n${2 + 3}!`];
// Hi
// 5!

This is useful for many tools which give special treatment to literals tagged by a particular name.

const html = [strings, ...values] => String.raw[{ raw: strings }, ...values];
// Some formatters will format this literal's content as HTML
const doc = html`
  
    
      Hello
    
    
      

Hello world!

`
;

Tagged templates and escape sequences

In normal template literals, the escape sequences in string literals are all allowed. Any other non-well-formed escape sequence is a syntax error. This includes:

  • \ followed by any decimal digit other than 0, or \0 followed by a decimal digit; for example \9 and \07 [which is a deprecated syntax]
  • \x followed by fewer than two hex digits [including none]; for example \xz
  • \u not followed by { and followed by fewer than four hex digits [including none]; for example \uz
  • \u{} enclosing an invalid Unicode code point — it contains a non-hex digit, or its value is greater than 10FFFF; for example \u{110000} and \u{z}

Note: \ followed by other characters, while they may be useless since nothing is escaped, are not syntax errors.

However, this is problematic for tagged templates, which, in addition to the "cooked" literal, also have access to the raw literals [escape sequences are preserved as-is].

Tagged templates should allow the embedding of languages [for example DSLs, or LaTeX], where other escapes sequences are common. Therefore, the syntax restriction of well-formed escape sequences is removed from tagged templates.

latex`\unicode`;
// Throws in older ECMAScript versions [ES2016 and earlier]
// SyntaxError: malformed Unicode character escape sequence

However, illegal escape sequences must still be represented in the "cooked" representation. They will show up as undefined element in the "cooked" array:

function latex[str] {
  return { cooked: str[0], raw: str.raw[0] };
}

latex`\unicode`;

// { cooked: undefined, raw: "\\unicode" }

Note that the escape-sequence restriction is only dropped from tagged templates, but not from untagged template literals:

const bad = `bad escape sequence: \unicode`;

Specifications

Specification
ECMAScript Language Specification
# sec-template-literals

Browser compatibility

BCD tables only load in the browser

See also

Bài Viết Liên Quan

Toplist mới

Bài mới nhất

Chủ Đề