JavaScript Template Literals - How to Use Template Strings in JavaScript



JavaScript Template Literals

  • Template Literals
  • Template Strings
  • String Templates
  • Back-Tics Syntax

Back-Tics Syntax

  • Template Literals back-ticks (``) used for the alternative quotes ("") to define a string.
javascript-template-literals

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Template Literals</h2>

<p>Template literals use back-ticks (``) to define a string:</p>

<p id="demo"></p>

<p>Template literals is not supported in Internet Explorer.</p>

<script>
let text = ``;
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Output

JavaScript Template Literals
Template literals use back-ticks (``) to define a string:
Template literals is not supported in Internet Explorer.

Quotes Inside Strings

  • With template literals,we can able to use the both single(‘ ’) & double (“ ”) quotes.
javascript-template-string-quotes

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Template Literals</h2>

<p>With template literals,we can able to use the both single(‘ ’) & double (“ ”) quotes:</p>

<p id="demo"></p>

<p>Template literals are not supported in Internet Explorer.</p>

<script>
let text = `He's is very good in "communication"`;
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Output

JavaScript Template Literals
With template literals,we can able to use the both single(‘ ’) & double (“ ”) quotes:
He's is very good in "communication"
Template literals are not supported in Internet Explorer.

Multiline Strings

  • Template literals allows multiline strings:
let text =
`The quick
brown fox
jumps over
the lazy dog`;

Interpolation

  • Template literals gives the simplest way to interpolate variables and expressions into strings.
  • The method is called string interpolation.

The syntax is:

${...}
javascript-template-literals-example

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Template Literals</h2>

<p>Template literals allows variables in strings:</p>

<p id="demo"></p>

<p>Template literals are not supported in Internet Explorer.</p>

<script>
let firstName = "venkat";
let lastName = "Kaashiv";

let text = `Welcome ${firstName}, ${lastName}!`;

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Output

JavaScript Template Literals
Template literals allows variables in strings:
Welcome venkat, Kaashiv!
Template literals are not supported in Internet Explorer.

Related Searches to JavaScript Template Literals - How to Use Template Strings in JavaScript