Suppose you’re working on a function for your web app, and that function outputs a long line of text. To make the output easier for your users to read, you’ll probably want to add a line break here and there.
What’s the best way to do this?
\n and inserts a line break on the screen.
However, there is a case where you might want to do something else, especially if you’re building a frontend, and we’ll get to it in a moment.
\n character where you want the line to break to show. If you’re writing HTML elements directly into the DOM, consider inserting a <br> element instead.
Read on for code examples and details as to why.
Adding a New Line to a String
To see how the newline character works in practice, let’s output the following haiku, a Japanese form of short poetry, by Katsushika Hokusai:
I will write, erase, rewrite
Erase again, and then
A poppy blooms.“A Poppy Blooms” by Katsushika Hokusai
Who knew coding had so much in common with poetry, right?
To output this haiku, we need to save it in a variable, making sure we preserve the line breaks as they are:
let poem = "I will write, erase, rewrite\nErase again, and then\nA poppy blooms"; console.log(poem);
If you opened up your browser’s developer tools right now (as I encourage you to do) and copy/paste this into the console, this is what you’d get:
Nine times out of ten, this should do the trick. But, as I mentioned, there’s one case where you may need to do something different, and that case is when you’re writing HTML to the DOM.
Adding a Line Break to the HTML Output
insertAdjacentHTML(), you will want to add your line breaks with a <br> element so that they render in the browser.
For example, let’s assume there’s a placeholder for a poem in a
<div> element with an ID of “poem:”
let poem = "I will write, erase, rewrite<br>Erase again, and then<br>A poppy blooms"; let placeholder = document.getElementById("demo"); placeholder.innerHTML = poem;
Notice that, instead of the
\n character, we’re inserting the
Were you to run this code, it would populate the placeholder
<div> with the poem, along with the necessary
<br> line breaks:
<div id="poem">I will write, erase, rewrite<br>Erase again, and then<br>A poppy blooms</div>
Job done 🙂