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

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.

主站蜘蛛池模板: 介休市| 普兰店市| 遵义县| 宝应县| 望城县| 茶陵县| 大田县| 依安县| 洛扎县| 苏尼特右旗| 启东市| 陈巴尔虎旗| 辽宁省| 高唐县| 微山县| 右玉县| 兴业县| 武邑县| 新竹县| 大丰市| 陇川县| 南汇区| 华蓥市| 大港区| 莱州市| 和田县| 胶南市| 阳朔县| 句容市| 方山县| 满洲里市| 大庆市| 南平市| 资溪县| 周宁县| 博兴县| 上高县| 南汇区| 伊春市| 鲜城| 建湖县|