In this article, we will learn different methods to add a new line in JavaScript strings, including escape sequences, template literals, and HTML line break tags.
Using Escape Sequences for New Lines
In JavaScript, when you want to add a new line within a string (i.e., to break text into multiple lines), escape sequences come in handy. These sequences are special characters that create a new line. The characters themselves are invisible in output but tell the browser where to break the text.
For example, if you are logging a message in the console but want to print each piece of information on a separate line, you may use the escape sequence \n
.
What is an Escape Sequence?
An escape sequence starts with a backslash (\
) and is followed by a character holding a special meaning. This combination allows inserting special characters into strings—characters that are otherwise difficult to type out directly. Some common escape sequences are as follows:
\n
: Inserts a new line in the text.\t
: Adds a tab indentation/space.\\
: Types out the literal backslash symbol (\
) in the string.\'
and\"
: Allows including single quotes in double-quoted strings or double quotes in a single-quoted string (e.g.,'I\'m a developer'
or"She said, \"Hello!\""
).
Escape sequences allow developers to format text in JavaScript in a much more readable way, especially in environments like web browsers and servers. For example, the character \n
is often used in server logs to separate each log entry, making them easier to read and scan through.
Example
let message = "Hello,\nWorld!";
console.log(message);
// Output:
// Hello,
// World!
Implementing Template Literals
Template literals allow you to write multiple lines without the need for escape sequences. Breaking a line using template literals is as easy as typing it out in a notepad. Like strings in JavaScript, template literals enclose a string using the backtick symbol (`) instead of single quotes or double quotes. This makes typed-out strings appear more natural and readable in contrast to if escape sequences had been utilized.
Advantages of Template Literals
Template literals are more powerful than you think! Not only can they gracefully handle new lines entered in code, but they let you place variables and other code right inside the string using the ${expression}
notation. This is more generally known as “string interpolation”. In contrast to string concatenation (i.e., the practice of joining strings using the +
operator), string interpolation provides a cleaner and more intuitive way to embed expressions within strings.
Example
let message = `Hello,
World!`;
console.log(message);
// Output:
// Hello,
// World!
let name = "Alice";
let greeting = `Hello,
${name}!`;
console.log(greeting);
// Output:
// Hello,
// Alice!
Using HTML Line Break Tags
In HTML, the line break tag <br>
is a quick and simple method to add line breaks in text. Like the JavaScript new line character \n
, you insert the <br>
tag in HTML where you’d like to break the line.
Using <br>
Tag in HTML with JavaScript
When working with JavaScript to dynamically change HTML content, the <br>
tag comes in handy. For example, when loading text from a file, you would have a string with newline escape sequences (\n
) for line breaks as opposed to HTML’s <br>
tag. These strings need to be treated by replacing \n
with <br>
before being assigned to an HTML content.
Example
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<div id="content"></div>
<script>
let message = "Hello,<br>World!";
document.getElementById("content").innerHTML = message;
</script>
</body>
</html>
// Output in the browser:
// Hello,
// World!
<!DOCTYPE html>
<html>
<head>
<title>Convert Newline to <br></title>
</head>
<body>
<div id="content"></div>
<script>
let message = "Hello,\nWorld!";
let formattedMessage = message.replaceAll("\n", "<br>");
document.getElementById("content").innerHTML = formattedMessage;
</script>
</body>
</html>
// Output in the browser:
// Hello,
// World!
Comparing Methods for Adding New Lines
One of the many challenges in front-end development is making the text look right, especially when you need to break lines. While this article covers three ways of doing so, the appropriate method varies depending on the context that it is used in:
- Using Escape Sequences (
\n
): Escape sequences are simple—simply add JavaScript line break (\n
) where you need a new line. It works for logging (console.log
) and anywhere where text is not placed inside HTML.let logMessage = "Error:\nLine 42\nUnexpected token"; console.log(logMessage); // Output: // Error: // Line 42 // Unexpected token
- **Template Literals (
)
: Template literals in JavaScript are more readable than having several escape sequences, and hence fancier! Simply encase strings in backticks and it is as if you’re typing out normal text. Plus, you get to perform string interpolation! It works best when you need to concatenate code in sections of a text.let logMessage = `Error: Line 42 Unexpected token`; console.log(logMessage); // Output: // Error: // Line 42 // Unexpected token
- HTML
<br>
Tag: When you need to display JavaScript strings on a web page, you need to switch line breaks to HTML break tags so that it correctly breaks lines in HTML. This is necessary whenever you’re dealing directly with website content.<!DOCTYPE html> <html> <head> <title>Line Break in HTML</title> </head> <body> <div id="error-message"></div><script> let errorMessage = "Error:\nLine 42\nUnexpected token"; let formattedErrorMessage = errorMessage.replaceAll("\n", "<br>"); document.getElementById("error-message").innerHTML = formattedErrorMessage; </script></body> </html> // Output in the browser: // Error: // Line 42 // Unexpected token
Common Mistakes to Avoid
As each method of adding a new line has its own contextual behavior, often you may end up making a mistake here and there while working with strings. Below are a few things to consider:
- At times, you may notice a literal escape sequence (
\n
) instead of a line break on your web page. This occurs when you forget to replace escape sequences with HTML break tags in JavaScript. Simply use theString.replaceAll("\n", "<br>")
method in JavaScript to solve the issue. - Make sure you use
replaceAll
instead of simplyreplace
in JavaScript to ensure all occurrences of\n
are replaced with HTML break tags. - Template literals must be enclosed using backticks, not quotes (` vs ‘). Although the symbols appear similar, they hold different meanings in JavaScript.
Best Practices for Adding New Lines in JavaScript
In JavaScript, adding new lines makes your output easy to read and your viewers will appreciate it. Depending on where and how you like the text to be displayed, you may have a few options at hand. Choosing the appropriate option is important to ensure you see the intended results.
- Choose the correct method to add a new line based on where the text is displayed. For example, use
\n
in JavaScript for logging or displaying messages on the server-side. If a text is to be displayed on a web page, use HTML line break tags (i.e.,<br>
). - Be consistent! When choosing to use
\n
for new lines, make sure this is applied across your project to avoid confusion and to maintain uniformity in your codebase. - Pick template literals when handling JavaScript multi-line strings and when your strings incorporate dynamic expressions. Template literals improve readability and eliminate the need for escaping quotes or explicitly adding newline characters.
F.A.Q
How do you add a new line in a JavaScript string?
To add a new line in a JavaScript string, you have a few methods. The most common one is by using the newline escape sequence character (\n
). Simply add the character anywhere you’d like to break a line. This works well when the text is to be displayed in JavaScript. When working with HTML, use the HTML <br>
tag instead of the escape sequence. If using template literals, simply type text in a new line as normal.
What is the difference between using \n
and <br>
in JavaScript?
The newline escape sequence (\n
) allows developers to display new lines in the context of JavaScript, such as in the console or in the filesystem (e.g., in log files). Escape sequences, however, do not display a new line in HTML. Rather, the HTML line break tag (<br>
) is placed where a line must be broken. Therefore, when working with JavaScript and HTML together, you will often find yourself translating strings between the two standards.
How do template literals help in adding new lines?
Template literals are
super handy in JavaScript. They give you the natural feel of writing text. A template literal encloses strings using the backtick symbol instead of quotes. Adding a line is as simple as typing text in a new line—no special characters or tags necessary! This improves the readability of your code as you begin encountering line breaks more often.