In this short tutorial, we look at multiple methods you can use to line break while dealing with strings in javascript.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
Table of Content
- What is a new line in Javascript?
- Breaking string using an Escape sequence
- New line using Template literals
- HTML Break Element
What is a new line in javascript?
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 which new lines can be added in javascript however it is not as simple as the paragraph or break tag we use in HTML. Nonetheless, let's look at the most commonly used methods.
Breaking strings using Escape sequence:
Escape sequences are the most 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 in a few older macs \r
is used. The implementation of escape sequences is quite straightforward. I have added a snippet below.
let flexiple = "Hire the top 1% freelance talent";
let new_flexiple = "Hire the \ntop 1% \nfreelance talent";
console.log(flexiple);
//Output: "Hire the top 1% freelance talent"
console.log(new_flexiple);
//Output: "Hire the
//top 1%
//freelance talent"
Note: Remember not to add spaces after the new line escape sequence as javascript would consider that to be a space and add it to the output as well.
New Line using Template Literals:
Template literals sound quite fancy, but underneath the jargon, they are just string literals that allow embedded expressions. This makes it easy to use multi-line strings. We do not enclose template literals with single or double quotes but rather with backtick (\
).
let flexiple = "Hire the \ntop 1% \nfreelance talent";
let new_flexiple = `Hire the
top 1%
freelance talent`;
console.log(flexiple);
//Output: "Hire the
//top 1%
//freelance talent"
console.log(new_flexiple);
//Output: "Hire the
//top 1%
//freelance talent"
In both cases, the same output is returned. but as you can see Template Literals make it quite simple to write multi-line strings.
HTML Break element
Adding HTML line break elements to your string is another method I have seen being used quite often. Though break elements must be used where the division of a line must be significant since this method is quite common we look at it as well.
<html>
<body>
<p id="newline"></p>
<script>
let flexiple = "Hire the" + "<br>" + "top 1% "+ "<br>" + "freelance talent";
document.getElementById("newline").innerHTML = flexiple;
</script>
</body>
</html>
Note: Remember to use the .innerHTML and not .innerText as you would with other text content.
Do let me know your thoughts/ queries in the comment section below.
Top comments (0)