How to Create Multi-Line Strings in JavaScript

Updated onbyAlan Morel
How to Create Multi-Line Strings in JavaScript

Strings in JavaScript are a sequence of unicode characters.

Depending on the situation, you might need to work with multi-line strings.

That is, strings that span multiple lines but are held inside a single variable.

There are many different ways to define a multi-line string in JavaScript and in this post we'll explore all of them.

Using newline characters

One of the ways you can create a multi-line string is by dividing up your string using newline characters.

These special characters don't get rendered when you try to print them, but they determine when a new line begins.

Let's create a multi-line string using newline characters.

JAVASCRIPT
const multiLineString = "First line\nSecond line\nThird line"; console.log(multiLineString);
BASH
First line Second line Third line

If it helps, you can also visually divide the string by adding a \ after the newline character.

Here's an example of this:

JAVASCRIPT
const multiLineString = "First line\n\ Second line\n\ Third line"; console.log(multiLineString);
BASH
First line Second line Third line

Using Template Literals

Template literals is a new feature introduced in ES6 that allows you to directly embed new lines inside your strings.

Template literals are surrounded by backtick characters, allowing the compiler to differentiate it from normal strings.

The great thing is that this allows you to use single and double quotes inside your strings.

Let's see an example of how to create a multi-line string using template literals:

JAVASCRIPT
const multiLineString = `First line Second line Third line`; console.log(multiLineString);
BASH
First line Second line Third line

When creating multi-line strings, using template literals are the recommended, more modern way to do it.

Conclusion

In this post, we learned how to initialize multi-line strings in JavaScript using two different ways.

Your options are to either manually insert newline characters or use template literals.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.