上QQ阅读APP看书,第一时间看更新
Writing multiline strings
Another feature of the new template literals is that they can span several lines. With earlier versions of JS, if you wanted to produce multiple lines of text, you had to insert newline characters ("\n") in the output string, like so:
let threeLines = "These are\nthree lines\nof text";
console.log(threeLines);
// These are
// three lines
// of text
With template strings, you can just write the line as desired:
let threeLines = `These are
three lines
of text`;
However, I would recommend against this practice. Even if the code may seem more legible, when it gets indented, the result looks ugly, since continuation lines must start at the first column—do you see why? Check out the following code—the continuation lines are pushed to the left, breaking the visual continuity of the indented code:
if (someCondition) {
.
.
.
if (anotherCondition) {
.
.
.
var threeLines = `These are
three lines
of text`;
}
}
You can use a backslash to escape characters that are not meant to be part of templating:
let notEscaped1 = `this is \$\{not\} interpolation\\nright? `;
// "this is ${not} interpolation\nright? "
You might want to look into String.raw (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw) for an alternative to this way of avoiding templating. You can just avoid templating altogether, since an informal poll has shown that practically no developers know of it and it isn't such a great advantage after all.