Add New Line In JavaScript with Example Codes


This is a short tutorial on how to add new lines in JavaScript string for console and DOM.

So, in JavaScript there are three ways of adding a new line depending on the output you want. Here, we will learn how we can output the new line in our console and in DOM.

Let's check out all the different ways along with example.

Using Escape Sequence to Print New Line In JavaScript

The escape sequence \n is a common way to create new line in JavaScript and many other programming languages.

To create new line using escape sequence \n, we just have to type it at the end of the line.

Example:

const normalLine = "hello coder. Learn about programming languages here."
const newLine = "hello coder.\nLearn about programming languages here."

console.log(normalLine)

console.log(newLine)

Output:

// normalLine
hello coder. Learn about programming languages here.
//newLine
hello coder. 
Learn about programming languages here.

NOTE:

DO NOT add space at the end of \n. It will add the space at the beginning of the new line.

Using Template Literals to Add New Line In JavaScript

Template Literals are string literals that provide easy ways to interpolate expressions in a string. These are literals delimited with back ticks ( ` ).

So to create new line or multi line in JavaScript we have to enclose the string inside (`) backticks and press Enter when we need a new line.

Example:

const str = `hello coder.
Learn about programming languages here.
Happy Coding`

console.log(str)

Output:

hello coder.
Learn about programming languages here.
Happy Coding

Template Literals makes it easy for us to create multi-line string in JavaScript.

The above two ways will output the result in a console. Now lets see how we can print it into a DOM using JavaScript.

New Line in DOM using JavaScript

To print out new line in a web-page we have to manipulate the DOM using <br > HTML element .

Using JavaScript, we can add the <br > element in a string and render it to our web-page.

Example of < br > in HTML code:

<body>
  <p>
    This is a webpage. <br />  This is a HTML element
  </p>
</body>

Output:

This a webpage.
This is a HTML element

So, using JavaScript we can get the same result by manipulation the DOM element with the innerHTML property and adding the <br > element inside the string.

Example:

<body>
  <div id="myText"></div>
  <script>
    let element = document.getElementById("myText");
    element.innerHTML = "This is a webpage. <br />  This is a HTML element";
  </script>
</body>

This script code will render the output with a newline with <br/> in the HTML page inside the <div> tag.

Output:

<div id="myText">
This is a webpage  <br />
This is a HTML element
</div>

Related Topics:

Single-line and Multi-line Comment | Javascript Comment


💾 Recommended Articles