Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript template strings

JavaScript template strings

Template strings in JavaScript are a convenient string syntax that allows you to embed expressions and variables in strings.

Template strings use backticks `` as string delimiters.

Template literals are literals delimited by backticks (`), allowing multiline strings, string interpolation with embedded expressions, and a special construct called tagged templates.

Syntax

`string text`



`string text line 1

 string text line 2`



`string text ${expression} string text`



tagFunction`string text ${expression} string text`

Parameters

Example

let text

=

`Hello RUNOOB

!

`

;

Try it »

Browser support

Template literals are a new feature of ES6 (JavaScript 2015), currently supported by some of the latest browser versions:

Chrome Edge Firefox Safari Opera
Supported Supported Supported Supported Supported

Single and double quotes can be used together in template strings:

Example

let

text

= `

He

'

s often called "Runoob"`;

Try it »

Template strings also support multiline text without special escape characters:

Example

const

multiLineText

=

`

  This is

  a multi

line

  text.

`

;

Try it »

To escape a backtick (`) in a template literal, add a backslash (\) before the backtick.

`\`` === "`"; // true

Template literals are enclosed in backticks (`), not in double quotes or single quotes.

In addition to ordinary strings, template literals can contain placeholders -- embedded expressions delimited by a dollar sign and curly braces: ${expression}.

The strings and placeholders are passed to a function (either the default function or a custom one). The default function (when no custom function is provided) only performs string interpolation to replace the placeholders and then concatenates the parts into a single string.

Template strings allow us to use variables:

Example

const

name

=

'

Runoob

'

;

const

age

=

30

;

const

message

= `

My

name

is

$

{

name

}

and

I

'

m ${age} years old.`;

Try it »

In the above example, the${name} and ${age} are the expression parts of a template string; they are included inside ${} and evaluated at runtime.

Template strings allow you to reference variables, call functions, and perform arbitrary JavaScript expressions inside a string.

Template strings allow us to use expressions:

Example

let price

=

10

;

let VAT

=

0.25

;

let total

=

`Total

:

$

{

(

price

(

1

VAT

)

)

.

toFixed

(

2

)

}

`

;

Try it »

Using template strings as HTML templates:

Example

let header

=

""

;

let tags

=

[

"RUNOOB"

,

"GOOGLE"

,

"TAOBAO"

]

;

let html

=

`

<h2${header}h2>
<ul`>

;

for

(

const

x of tags

)

{

  html

+=

`

<

li

$

{

x

}

li

`

;

}

html

+=

`

ul

`

;

Try it »