Various methods for a Javascript new line

In this short tutorial, we look at multiple javascript new line methods and how you can use line break while dealing with strings.

Table of Contents - Javascript new line

What is JavaScript new line?

Manipulating strings in JavaScript can be a hassle. Although string manipulation is easy to learn, implementing them is tricky and one similar area is adding new lines.

There are many ways in JavaScript for new lines, however, they are not as simple as the paragraph or break tag we use in HTML.

Nonetheless, let's look at the most commonly used JavaScript new line methods.

Breaking strings using Escape sequence:

Escape sequences are a commonly used method to create a new line in JavaScript.

The escape sequence used to create a new line in Windows and Linux is \n, but for a few older macs \r is used. The implementation of escape sequences is quite straightforward.

let flexiple = "Hire the top 1% freelance talent"; 

let newstring = "Hire the \ntop 1% \nfreelance talent"; 

//Output: "Hire the top 1% freelance talent" 

//Output: "Hire the 
//top 1% 
//freelance talent"

Note: Do not add spaces after the new line escape sequence as JavaScript would consider that to be a space and add it to the output.

New Line using Template Literals:

Template literals sound quite fancy, but underneath the jargon, they are just string literals that allow embedded expressions.

They make it easier to use multi-line strings. Template literals are enclosed within the backtick (` `).

let flexiple = "Hire the \ntop 1% \nfreelance talent"; 

let newstring = `Hire the 
top 1% 
freelance talent`; 

//Output: "Hire the 
//top 1% 
//freelance talent"

//Output: "Hire the 
//top 1% 
//freelance talent"

In both cases, the same output is returned. but as you can see Template Literals make it easier to write multi-line strings.

HTML Break element

Adding HTML line break elements to your string is another method to add a JavaScript new line.

Note that break elements must be used only where the division of a line needs to be significant. But since this method is quite common we look at it as well.

<p id="newline"></p> 

let flexiple = "Hire the" + "<br>" + "top 1% "+ "<br>" + "freelance talent"; 

document.getElementById("newline").innerHTML = flexiple; 


Note: Remember to use the .innerHTML and not .innerText as you would with other text content.

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

Copyright @2023 Flexiple Inc