How to add new lines to console and DOM output in JavaScript

Updated onbyAlan Morel
How to add new lines to console and DOM output in JavaScript

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.

JAVASCRIPT
const string = "Hello\nWorld"; console.log(string);
BASH
Hello 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.

JAVASCRIPT
const string = `Hello World`; console.log(string);
BASH
Hello 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:

JAVASCRIPT
const string = "Hello<br>World"; document.body.innerHTML = string;
BASH
Hello World

Another way to do this is by writing to the document object:

JAVASCRIPT
document.write("Hello<br>World");
BASH
Hello 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!

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.