DEV Community

loading...

How to Create Multi-Line String with Template Literals

samanthaming profile image Samantha Ming ・3 min read

Code Tidbit by SamanthaMing.com

With the arrival of Template Literals, it's finally super easy to produce multi-line strings. Previously, we had to use the \n or separate string concatenation which was messy and difficult to read. Finally, it’s easier now. ES6 for the win 🙌

// Old way
const multiLine1 = "1️⃣first \n2️⃣second";

// ✅ ES6 way
const multiLine2 = `1️⃣first
2️⃣second`;

/* RESULT
1️⃣first
2️⃣second
*/

Multi-line vs Single-line Strings

I just want to make sure I clarify that when I say "Multi-Line", I mean the output of the string is spanning on multiple lines. For example, if I console.log the variable, it will produce something like this:

// Multi-Line

1️⃣first
2️⃣second

And here's a "Single-Line" output:

// Single-Line

1️⃣first 2️⃣second

The reason why I'm emphasizing this is because there are other methods in JavaScript to create strings. But watch out, they actually don't produce true "Multi-Line" outputs 😱

Ex. Using +

const notTrueMultiLine = '1️⃣first' +
'2️⃣second' +
'3️⃣three';

console.log(notTrueMultiLine);
// 1️⃣first2️⃣second3️⃣three

Ex. Using \

const notTrueMultiLine = "\
1️⃣first \
2️⃣second \
3️⃣three";

console.log(notTrueMultiLine);
// 1️⃣first2️⃣second3️⃣three

Even though, it may appear in your code as multi-line. But when it's outputted, it's actually a single-line. To create true multi-line output, you have to use Template Literals or \n. Just wanted to make sure I point this out cause I remember making this mistake when I was first learning JavaScript 😖

Blank Space in Template Literals

So template literals will output as it appears, spaces and all! Because of that, be mindful of your blank spaces or lines.

const blankSpace = `
first
    second
  third

`;

Here's the output. I denoted the white space with a dot, ⚪️ and line break with a square ◻️:

□
first
····second
··third
□
□

HTML Templating with Template Literals

This is my favorite use case of using template literals multi-string capability. It makes super readable and easy to render HTML markup. I remember before, the only way to do this is to use a template system such as Handlebars.js. Well, not anymore. We can achieve the same result without importing anything and just use vanilla JS. It's awesome! Anyhoo, let's take a look at some examples:

✅Ex. HTML Markup using Template Literals

const HTMLmarkup = `
<article>
  <h1>Code Tidbits</h1>
</article>
`;

Ex. HTML Markup using Old JavaScript

const HTMLmarkup = "<article>" +
"<h1>Code Tidbits</h1>" + 
"</article>";

Ex. HTML Markup using Handlebars.js

<script id="entry-template" type="text/x-handlebars-template">
  <article>
    <h1>Code Tidbits</h1>
  </article>
</script>

<!-- also need to import handlebars -->

Resources


Thanks for reading ❤
Say Hello! Instagram | Twitter | Facebook | Medium | Blog

Discussion (12)

pic
Editor guide
Collapse
flrnd profile image
Florian Rand

Another good addition to template literals is writing more readable code, for example:

const name = 'Peter'
const age = 35

//instead of the classic concatenation
console.log(name + " is only " + age + " old!")

//we can write something like this:
console.log(`${name} is only ${age} old!`)
Collapse
qcgm1978 profile image
Youth

It also works

console.log(`%s is only %d old!`,name,age)
Collapse
samanthaming profile image
Samantha Ming Author

Totally! String interpolation is probably one of my most used ES6 feature 💯

Collapse
flrnd profile image
Florian Rand

Same here! Btw I forgot to mention great article! (Concentrated writing the example totally forgot about being polite 😁)

Thread Thread
samanthaming profile image
Samantha Ming Author

You’re welcome! Btw, thanks for jumping back and leaving this kind comment 😊 You’re making this community really nice to a part of 💛

Collapse
daviddalbusco profile image
David Dal Busco

Interesting. Does it work cross OS?

Let's say I implement the "ES6 console.log way - first example here above" on a Unix kernel, if I share the code with someone on a Windows kernel, it will be interpreted with "multi-lines" too (\n vs \r\n)?

Collapse
flrnd profile image
Florian Rand

JavaScript runs in the browser 😅

Collapse
daviddalbusco profile image
David Dal Busco

Hahaha it should yes 😂

Let's say that my question applies in case I would run the code on the API side or as a local script 😉

It's probably good, I just that I faced so often encoding errors in the past that I was curious about it

Thread Thread
flrnd profile image
Florian Rand

Interesting, Im going ti do some tests later at home with a Windows machine

Thread Thread
daviddalbusco profile image
David Dal Busco

Super cool 🚀

Collapse
namstel profile image
Namstel

I love template literals. I remember having to write HTML templates with the '"\n" +'-notation. So messy, so easy to make mistakes. Great article for beginners!

Collapse
samanthaming profile image
Samantha Ming Author

Same! And you pointed out the biggest benefit, it helps reduce errors. That’s why clean code so important, it makes it easier to spot errors. And template literals definitely accomplishes that! 💯