Adding a New line to String or in DOM output in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
5 min

banner

# Table of Contents

  1. Adding new lines to a string in JavaScript
  2. Adding new lines to the DOM (in HTML output)

If you need to add new lines to the DOM (in HTML output), click on the second subheading.

# Adding new lines to a string in JavaScript

Use the \n character to add a new line to a string in JavaScript.

The \n character is the universal line feed character and inserts a newline in the string.

index.js
const str = 'bobby\nhadz\ncom'; console.log(str);

The code sample produces the following output.

output
bobby hadz com

add newline using n character

The code for this article is available on GitHub

Here is another example.

index.js
const str = 'first line\nsecond line\nthird line'; console.log(str);

Output:

output
first line second line third line
The code for this article is available on GitHub

The \n character is the universal line feed character and is used to insert a newline in JavaScript strings.

Note that adding spaces before or after the \n character will affect the output.
index.js
const str = 'first line \n second line\nthird line'; console.log(str);

Output:

shell
first line second line third line

adding spaces affects output

The code for this article is available on GitHub

# Using the addition (+) operator to add a new line to a String

You can also use the addition (+) operator to add a new line to a string.

index.js
const str = 'bobby'; const result = str + '\n' + 'hadz' + '\n' + 'com'; console.log(result);

Output:

output
bobby hadz com

add newline using n character

The code for this article is available on GitHub

The addition (+) operator concatenates the strings with newline characters in between.

# Using a template literal to add new lines to a String

You can also use a template literal to add new lines to a string.

Template literals are strings that are delimited by backticks `` (not single quotes).

index.js
const str = `first line second line third line`; console.log(str);

Output:

output
first line second line third line

add newline using template literal

The code for this article is available on GitHub

Template literals preserve whitespace and newlines.

Template literals allow for multi-line strings without explicitly having to add newline \n characters for line breaks.

You can use the dollar sign ${} curly braces syntax if you need to interpolate variables in your multi-line string.

index.js
const first = 'bobby'; const last = 'hadz'; const str = `123 ${first} 345 ${last} third line`; console.log(str);

Output:

shell
123 bobby 345 hadz third line

multiline string with variables

The code for this article is available on GitHub

# Join the elements of an array with new lines

If you need to join the elements of an array with newline characters, use the Array.join() method.

index.js
const arr = ['bobby', 'hadz', 'com']; const result = arr.join('\n'); console.log(result);

Output:

shell
bobby hadz com

add newline using n character

The code for this article is available on GitHub

We passed a newline as the separator to the Array.join() method to have each array element on a separate line.

# Iterating over the array and adding a newline character to each string

A for...of loop can also be used to iterate over the array and add a newline \n character to each string.

index.js
const arr = ['bobby', 'hadz', 'com']; let result = ''; for (const element of arr) { result += element + '\n'; } console.log(result);

Output:

output
bobby hadz com

for loop add newline

The code for this article is available on GitHub

Notice that there is a trailing newline (\n) character.

If you don't want the trailing newline character, use the Array.join() method from the previous code sample or the String.trim() method.
index.js
const arr = ['bobby', 'hadz', 'com']; let result = ''; for (const element of arr) { result += element + '\n'; } console.log(result.trim());

Output:

output
bobby hadz com

The String.trim() method removes the leading and trailing whitespace (including newlines) from the string.

# Adding new lines to the DOM (in HTML output)

You can use the <br /> HTML element to add new lines to the DOM. The <br /> tag produces a line break in the text.

The text after the <br /> tags begins at the start of the next line.

Assume, we start with the following HTML code.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

The code simply loads a JavaScript file called index.js.

Here is the code for the index.js file.

index.js
document.write('First line<br />Second line<br />Third line');

adding new line to dom

The code for this article is available on GitHub

As shown in the screenshot, the br tags got inserted where specified and rendered the sentence on multiple lines.

# \n characters don't affect the layout in the DOM

Note that \n characters are not used to add new lines in the HTML output. Instead, you should use <br /> tags.

If you add an \n character to the DOM, the string will only take a single line as \n characters don't affect the layout.

# Appending text with new lines to a specific DOM element

Here is the HTML code for the example.

index.html
<body> <div id="box"></div> <script src="index.js"></script> </body>
The code for this article is available on GitHub

Let's use the innerHTML attribute to append text with new lines to the div element.

index.js
const box = document.getElementById('box'); box.innerHTML = 'First line<br />Second line<br />Third line';

using innerhtml property to add newlines

We used the document.getElementById method to select the div by its id attribute.

As shown in the screenshot, we appended 3 lines of text to the div element that has an id of box.

# Using the addition (+) operator to append a string with new lines to the DOM

You can also use the addition (+) operator to append a string with new lines to the DOM.

index.js
const box = document.getElementById('box'); const first = 'First line'; const second = 'Second line'; const third = 'Third line'; box.innerHTML = first + '<br />' + second + '<br />' + third;

add new lines to dom with addition operator

The code for this article is available on GitHub

We used the addition (+) operator to concatenate the <br /> tags to the strings.

# Use a template literal instead of a regular string

Use a template literal instead of a regular string to make your code more readable.

Note that template literals are strings that are delimited by backticks `` (not single quotes).
index.js
const box = document.getElementById('box'); box.innerHTML = `First line<br /> second line<br /> third line`;

using innerhtml property to add newlines

The code for this article is available on GitHub

The code sample produces the same output.

Here is the HTML equivalent of the code.

index.html
<div id="box"> First line<br> second line<br> third line </div>

Template literals allow for multi-line strings without explicitly having to add newline \n characters for line breaks.

Template literals preserve whitespace and newlines.

You can use the dollar sign ${} curly braces syntax if you need to interpolate variables in your multi-line string.

index.js
const box = document.getElementById('box'); const first = 'bobby'; const last = 'hadz'; box.innerHTML = `${first}<br /> ${last}<br /> third line`;

adding newlines and variables in html output

# Append a string with newlines to the DOM from an array

If you have an array of strings, use the Array.join() method to join the array elements into a string with a newline (<br />) separator.

index.js
const box = document.getElementById('box'); const arr = ['First line', 'Second line', 'Third line']; const str = arr.join('<br />'); box.innerHTML = str;

append to dom with newline from array

The code for this article is available on GitHub

# Using a for...of loop to append a string with newlines to the DOM

A for...of loop can also be used to iterate over the array and add a newline \n character to each string.

index.js
const box = document.getElementById('box'); const arr = ['First line', 'Second line', 'Third line']; let result = ''; for (const element of arr) { result += element + '<br />'; } box.innerHTML = result;

for loop add newline to dom

The code for this article is available on GitHub

Notice that there is a trailing newline (<br />) tag after the last array element.

If you don't want the trailing <br /> tag, use the Array.join() method from the previous example or the String.slice() method.

index.js
const box = document.getElementById('box'); const arr = ['First line', 'Second line', 'Third line']; let result = ''; for (const element of arr) { result += element + '<br />'; } result = result.slice(0, result.lastIndexOf('<')); box.innerHTML = result;

no more trailing br tag

The code for this article is available on GitHub

We used the String.slice() method to get a slice of the string up to the last angle bracket <.

This way, the trailing <br /> tag is not added to the DOM.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.