How to Output Line Breaks in HTML Using JavaScript?

Estimated read time 1 min read

In HTML, you can use the <br> element to create line breaks. In JavaScript, you can add line breaks to HTML content by concatenating the string with the <br> tag.

Here’s an example:

let stringWithLineBreaks = "Line 1\nLine 2\nLine 3";
let htmlString = stringWithLineBreaks.replace(/\n/g, "<br>");
document.getElementById("targetDiv").innerHTML = htmlString;

This will replace all occurrences of the newline character \n with the <br> tag in the stringWithLineBreaks variable and then set the HTML content of the targetDiv element to the resulting string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply