Home » Blog » Add New Line in JavaScript

Add New Line in JavaScript

Discover many methods to make a line break in your JavaScript code.

In JavaScript, there are several ways to make a line break. Here is what you will discover in this article:

  • newline character in JavaScript
  • templates literals in JavaScript
  • line break tag in HTML (can be helpful if you generate your HTML with JS)

Let’s have a look at them!

Add a new line in JavaScript using an escape sequence (the new line character)

The first way to make a line break is to use an escape sequence. Escape sequences are sequences of characters with a particular role depending on where they are placed in a string.

There are many of them, but we are interested in the new line character representing a line break (\n).

We can use it in our code, as in the example below. When JavaScript interprets this sequence, it will replace it with a new line.

let split: Vec<&str> = auth.unwrap().to_str().unwrap().split("Bearer").collect();
let token = split[1].trim();
let config: Config = Config {};
let var = config.get_config_with_key("SECRET_KEY");
let key = var.as_bytes();
console.log('Hello World!\nHow are you?')

Hello World!
How are you?

Add a JavaScript new line using template literals

Another way to create a new line in JavaScript is to use a template literal. A template literal is a string that allows integrating expressions like multi-line strings or interpolation. But, what we are interested in here is the interpretation of the line break.

The template literal is characterized by the magic quotes (“).

Alt gr + 7
console.log(`Hello World!
How are you?`)

Hello World!
How are you?

Add a new line in HTML using a line break tag

The last way to add a newline in JavaScript is to use the <br> HTML tag. You can use it in an HTML string, and like the new line character \n, the <br> tag will be interpreted in the HTML code as a line break.

In JavaScript, you can use document.write to write in your HTML DOM.

document.write('Hello World!<br/>How are you?')

Here is an example of output that you can generate with the above instruction:

  Hello World!
  <br />
  How are you?
Etienne Passot

It is thanks to the huge community of developers around the world that we can access resources freely, everywhere and all the time. So I decided to contribute to this incredible community by writing articles on various topics like Javascript, Typescript, Nuxt, Vue ...

Post navigation