How to Add New Line in JavaScript
Today we will learn how to add a new line in JavaScript directly in text and with an HTML attribute.
Add New Line to Console Output With \n
The \n
keyword is what creates a new line in the browser console. To demonstrate this, let's create a string of text containing \n
and output it to the console.
var str = 'Hello\nworld!';
console.log(str);
Hello
world!
Add New Line with Multiline JavsScript String
To create multiline strings in JavaScript wrap the string in `` (backquotes). Multiline strings allow us to create new line with the ENTER key like this:
var str = `Hello
world!`;
console.log(str);
Hello
world!
Add New Line to HTML DOM with the br Tag
To add new lines to an HTML document, use the HTML br
tag. Here is an example of adding a string of text containing a line break to a div
element:
var str = 'Hello <br> world!';
document.getElementById('wrapper').innerHTML = str;
Hello
world!