- Various methods for a Javascript new line
- Table of Contents — Javascript new line
- What is JavaScript new line?
- Breaking strings using Escape sequence:
- New Line using Template Literals:
- HTML Break element
- String with new line javascript
- # Table of Contents
- # Adding new lines to a string in JavaScript
- # Using the addition (+) operator to add a new line to a String
- # Using a template literal to add new lines to a String
- # Join the elements of an array with new lines
- # Iterating over the array and adding a newline character to each string
- # Adding new lines to the DOM (in HTML output)
- # \n characters don’t affect the layout in the DOM
- # Appending text with new lines to a specific DOM element
- # Using the addition (+) operator to append a string with new lines to the DOM
- # Use a template literal instead of a regular string
- # Append a string with newlines to the DOM from an array
- # Using a for. of loop to append a string with newlines to the DOM
- # Additional Resources
- How to add a new line to a JavaScript string
- A newline character
- Backticks
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"; console.log(flexiple); //Output: "Hire the top 1% freelance talent" console.log(newstring); //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`; console.log(flexiple); //Output: "Hire the //top 1% //freelance talent" console.log(newstring); //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.
let flexiple = "Hire the" + "
" + "top 1% "+ "
" + "freelance talent"; document.getElementById("newline").innerHTML = flexiple;
Note: Remember to use the .innerHTML and not .innerText as you would with other text content.
String with new line javascript
Last updated: Feb 25, 2023
Reading time · 5 min
# Table of Contents
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.
Copied!const str = 'bobby\nhadz\ncom'; console.log(str);
The code sample produces the following output.
Copied!const str = 'first line\nsecond line\nthird line'; console.log(str);
Copied!first line second line third line
The \n character is the universal line feed character and is used to insert a newline in JavaScript strings.
Copied!const str = 'first line \n second line\nthird line'; console.log(str);
Copied!first line second line third line
# 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.
Copied!const str = 'bobby'; const result = str + '\n' + 'hadz' + '\n' + 'com'; console.log(result);
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).
Copied!const str = `first line second line third line`; console.log(str);
Copied!first line second line third line
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.
Copied!const first = 'bobby'; const last = 'hadz'; const str = `123 $first> 345 $last> third line`; console.log(str);
Copied!123 bobby 345 hadz third line
# 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.
Copied!const arr = ['bobby', 'hadz', 'com']; const result = arr.join('\n'); console.log(result);
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.
Copied!const arr = ['bobby', 'hadz', 'com']; let result = ''; for (const element of arr) result += element + '\n'; > console.log(result);
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.
Copied!const arr = ['bobby', 'hadz', 'com']; let result = ''; for (const element of arr) result += element + '\n'; > console.log(result.trim());
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
HTML element to add new lines to the DOM. The
tag produces a line break in the text.
The text after the
tags begins at the start of the next line.
Assume, we start with the following HTML code.
Copied!DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> script src="index.js"> script> body> html>
The code simply loads a JavaScript file called index.js .
Here is the code for the index.js file.
Copied!document.write('First line
Second line
Third line');
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
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.
Copied!body> div id="box">div> script src="index.js"> script> body>
Let’s use the innerHTML attribute to append text with new lines to the div element.
Copied!const box = document.getElementById('box'); box.innerHTML = 'First line
Second line
Third line';
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.
Copied!const box = document.getElementById('box'); const first = 'First line'; const second = 'Second line'; const third = 'Third line'; box.innerHTML = first + '
' + second + '
' + third;
We used the addition (+) operator to concatenate the
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.
Copied!const box = document.getElementById('box'); box.innerHTML = `First linebr /> second linebr /> third line`;
The code sample produces the same output.
Here is the HTML equivalent of the code.
Copied!div id="box"> First linebr> second linebr> 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.
Copied!const box = document.getElementById('box'); const first = 'bobby'; const last = 'hadz'; box.innerHTML = `$first>br /> $last>br /> third line`;
# 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 (
) separator.
Copied!const box = document.getElementById('box'); const arr = ['First line', 'Second line', 'Third line']; const str = arr.join('
'); box.innerHTML = str;
# 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.
Copied!const box = document.getElementById('box'); const arr = ['First line', 'Second line', 'Third line']; let result = ''; for (const element of arr) result += element + '
'; > box.innerHTML = result;
Notice that there is a trailing newline (
) tag after the last array element.
If you don’t want the trailing
tag, use the Array.join() method from the previous example or the String.slice() method.
Copied!const box = document.getElementById('box'); const arr = ['First line', 'Second line', 'Third line']; let result = ''; for (const element of arr) result += element + '
'; > result = result.slice(0, result.lastIndexOf(')); box.innerHTML = result;
We used the String.slice() method to get a slice of the string up to the last angle bracket < .
This way, the trailing
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.
How to add a new line to a JavaScript string
You can add a line break to your JavaScript strings, by using the \n symbol or backticks. Here’s how it’s done.
A newline character
The most straightforward way to add a new line to a string in JavaScript is by using a newline character. It’s spelled at \n .
const oneStringTwoLines = `Hello,\nWorld!`; console.log(oneStringTwoLines);
First line ends right after the \n character, and the second part of the string is printed on a new line.
Backticks
When you use backticks to declare strings in JS, you can just press Enter to move to a new line. Line break will be added automatically.
const s = `this string takes multiple lines`; console.log(s);
Here’s what you’ll see in the console.
this string takes multiple lines