How to use template literals In Javascript

The strings are delimited using backticks, unlike normal single/double quotes delimiter. 

Example: This example uses template literals to create multi-line strings. 

html
<h1 style="color: green">
    w3wiki
</h1>

<b>
    How to create multi-line
    strings in JavaScript?
</b>

<div class="multiline"></div>

<p>
    Click on the button to
    insert multiline text
</p>

<button onclick="showMultiline()">
    Click here
</button>

<script type="text/javascript">
    function showMultiline() {
        multilineString =
            `<div>
                <h3>This is the heading</h3>
                <p>
                    This is a paragraph. This uses
                    template literals that were
                    added in ES6 of JavaScript
                </p>
            </div>`
        
        document.querySelector('.multiline').innerHTML
                = multilineString;
    }
</script>

Output:

How to create multi-line strings in JavaScript?

How to create multi-line strings in JavaScript ?

In JavaScript, the absence of native support for multi-line strings was a longstanding challenge. However, with the advent of ES6 (ECMAScript 2015), the things changed dramatically. ES6 introduced string literals, offering robust support for multi-line strings, which was a significant enhancement for developers.

In this article, we’ll see the evolution of multi-line string handling in JavaScript, exploring how ES6 string literals revolutionized the way developers work with text data. We’ll also discuss various strategies for managing multi-line strings, especially for scenarios where compatibility with older browsers remains a priority.

Table of Content

  • Method 1: Using template literals
  • Method 2: Using the backslash to escape the literal newlines
  • Method 3: Concatenating the individual strings together.


Similar Reads

Method 1: Using template literals

The strings are delimited using backticks, unlike normal single/double quotes delimiter....

Method 2: Using the backslash to escape the literal newlines

The other method that can be used to create multi-line strings is escaping every newline on each line....

Method 3: Concatenating the individual strings together.

The simplest, but cumbersome way is separating each line as a string and concatenating it into one final string....