Categories
JavaScript Answers

How to convert \n to HTML line breaks?

Spread the love

Sometimes, we want to convert \n to HTML line breaks.

In this article, we’ll look at how to convert \n to HTML line breaks.

How to convert \n to HTML line breaks?

To convert \n to HTML line breaks, we can set the white-space CSS property to pre-line.

For instance, we write:

<span style="white-space: pre-line"></span>

to add a span with the white-space CSS property set to pre-line.

Then we write:

const span = document.querySelector('span')
span.textContent = 'foo \n bar'

We select the span with document.querySelector.

And then we set the textContent of the span to 'foo \n bar' to set that as the content of the span.

Now we should see:

foo
bar

displayed on the screen.

Conclusion

To convert \n to HTML line breaks, we can set the white-space CSS property to pre-line.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *