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.
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.
\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.
const string = "Hello\nWorld"; console.log(string);
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.
const string = `Hello World`; console.log(string);
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.
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:
const string = "Hello<br>World"; document.body.innerHTML = string;
Another way to do this is by writing to the
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!
Leave us a message!