官术网_书友最值得收藏!

Template strings

Template strings are very simple, but they are an extremely useful addition to the JavaScript syntax. They serve three main purposes:

  • Writing multiline strings
  • String interpolation
  • Tagged template strings

Before template strings, it was quite verbose to write multiline strings. You needed to concatenate pieces of strings and append a new-line character yourself to the line endings:

const header = '<header>\n' + 
' <h1>' + title + '</h1>\n' +
'</header>';

Using template strings, we can simplify this example a lot. We can write multiline strings, and we can also use the string interpolation functionality for our title variable that we used to concatenate earlier:

const header = ` 
<header>
<h1>${title}</h1>
</header>
`;

Note the back ticks instead of the previous single quotes. Template strings are always written between back ticks, and the parser will interpret all characters in-between them as part of the resulting string. This way, the new-line characters present in our source file will also be part of the string automatically.

You can also see that we have used the dollar sign, followed by curly brackets to interpolate our strings. This allows us to write arbitrary JavaScript within strings and helps a lot while constructing HTML template strings.

You can read more about template strings on the Mozilla Developer Network.

主站蜘蛛池模板: 南通市| 堆龙德庆县| 清徐县| 吉首市| 资兴市| 平塘县| 横峰县| 保亭| 揭西县| 万盛区| 宁晋县| 新龙县| 齐河县| 吴川市| 松溪县| 太白县| 凤台县| 临沧市| 山西省| 太保市| 肃宁县| 民县| 尤溪县| 新密市| 宜宾市| 曲麻莱县| 朝阳县| 安丘市| 荥阳市| 阿鲁科尔沁旗| 广安市| 茌平县| 长子县| 抚宁县| 吐鲁番市| 梅州市| 阿拉尔市| 禄丰县| 临沂市| 中牟县| 墨竹工卡县|