How to Create Multi-Line Strings in JavaScript
Table of Contents
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.
JAVASCRIPTconst multiLineString = "First line\nSecond line\nThird line";
console.log(multiLineString);
BASHFirst 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:
JAVASCRIPTconst multiLineString = "First line\n\
Second line\n\
Third line";
console.log(multiLineString);
BASHFirst 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:
JAVASCRIPTconst multiLineString = `First line
Second line
Third line`;
console.log(multiLineString);
BASHFirst 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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Learn how to build a Slack Bot using Node.js