This is the 24th day of my participation in the August More Text Challenge
Template string
In ES6 and later, string text can be delimited with backapostrophes:
let s = `hello world`;
Copy the code
However, this is not just another string text syntax, because these template texts can contain any JavaScript expression. Calculates the final value of the string text in the backapostrophe by evaluating any contained expressions, converting the values of those expressions to strings, and combining those computed strings with the text characters in the backapostrophe:
let name = "Chen";
let greeting = `Hello ${ name }. `; // greeting == "Hello Chen."
Copy the code
Everything between ${and matched} is interpreted as a JavaScript expression. Everything outside the braces is plain string text. Evaluate the expression inside the braces, then convert it to a string and insert it into the template, replacing the dollar sign, the braces, and everything in between.
Template text can contain any number of expressions. It can use any escape character that normal strings can use, and it can span any number of lines without special escape. The following template text contains four JavaScript expressions, a Unicode escape sequence, and at least four line breaks (the expression value may also include line breaks) :
let errorMessage = `\
\u2718 Test failure at ${filename}:${linenumber}:
${exception.message}
Stack trace:
${exception.stack} `;
Copy the code
– The backslash at the end of the first line escapes the initial newline, so the result string starts with the Unicode – character (\u2718) instead of a newline.
Tag template text
A powerful but less commonly used feature of template text is that if the function name (or “tag”) just precedes the opening backapostrophe, the value of the text and the expression in the template text is passed to the function. The value of the tag template text is the return value of the function. For example, this can be used to apply HTML or SQL escapes to values before replacing them with text.
ES6 has a built-in markup function: string.raw (). It returns the text inside the backapostrophe and does not handle backslash escapes:
`\n`.length // => 1: the string has only one newline character
String.raw`\n`.length // => 2: backslash and letter N
Copy the code
Note that even though the tag part of the tag template text is a function, it is called without parentheses. In this very special case, the backapostrophe character replaces the open and close parentheses.
The ability to define your own template tag functions is a powerful feature of JavaScript. These functions do not need to return strings; they can be used like constructors to define new text syntax for the language.