Allowing string interpolation and line breaks inside strings in Javascript

marlonbrum

Márlon Medeiros Brum

Posted on July 3, 2020

Allowing string interpolation and line breaks inside strings in Javascript

In Javascript, when you have to build a multiline string, you'll probably do that:

let myLabelText = getLabelText();
let myInputValue = getInputValue();

let sHtml = "<div class='outter-container'>"
             + "<div class='inner-container'>"
             + "<label for='myInput'>" + myLabelText + "</label>"
             + "<input id='myInput' value='" + myInputValue + "' />"
             + "</div>"
             + "</div>";

In my opinion the readability of the code is not so good. I've recently discovered that by the use of backticks (`) to delimiter strings, you can use string interpolation and insert line breaks in the strings.

String interpolation is the ability to reference variables from inside the string, without the need to concatenate them. This way, the code above could be rewritten like this:

let myLabelText = getLabelText();
let myInputValue = getInputValue();

let sHtml = `<div class='outter-container'>
               <div class='inner-container'>
                 <label for='myInput'>${myLabelText}</label>
                 <input id='myInput' value='${myInputValue}' />
               </div>
             </div>`;

The code is much more cleaner, without the extra chars to close and open strings.

💖 💪 🙅 🚩
marlonbrum
Márlon Medeiros Brum

Posted on July 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related