When you have a string and want to display it on the screen, you might need to create line breaks in the string to aid with readability.
There are two main ways to display a string in JavaScript and that is through the console or by adding it directly to your HTML.
In this post, we'll learn how to output strings with line breaks in JavaScript.
Adding new lines in your console
The most common scenario is outputting a line with line breaks to the console.
To add a new line in your string, simply use the new line character (\n) in your string.
The \n character is used to create a new line in the string, turning the string into a multi-line string.
When you log it to the console, it will automatically create a new line for you.
JAVASCRIPTconst string = "Hello\nWorld";
console.log(string);
BASHHello
World
If you don't want to use \n to create a new line, you can make use of template literals.
Template literals are strings that can contain new line breaks formed when pressing enter.
JAVASCRIPTconst string = `Hello
World`;
console.log(string);
BASHHello
World
Because template literals also support interpolation, they are the recommended way to add line breaks to a string, especially because they are arguably more readable as well.
Adding new lines in your HTML
If you prefer to see your string as a multi-line string in your HTML, you can use the <br> tag to create a new line.
One way to easily inject HTML is to write it directly to the document:
JAVASCRIPTconst string = "Hello<br>World";
document.body.innerHTML = string;
BASHHello
World
Another way to do this is by writing to the document object:
JAVASCRIPTdocument.write("Hello<br>World");
BASHHello
World
Conclusion
In this post, we learned how to output strings with line breaks in JavaScript.
Simply use the \n character to create a new line in your string or use the <br> tag to create a new line in your HTML.
Thanks for reading!
How to Install Node on Windows, macOS and Linux
Managing PHP Dependencies with Composer
Create an RSS Reader in Node
How to Set Up Cron Jobs in Linux
How to build a Discord bot using TypeScript
Build a Real-Time Chat App with Node, Express, and Socket.io
Learn how to build a Slack Bot using Node.js
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with React
Getting Started with Vuex: Managing State in Vue
How To Create a Modal Popup Box with CSS and JavaScript
