0

I have a string that looks like this:

const multiLine = "This is line 1\nThis is line2\nThis is line3";

How do I display it to browser as multi-line at the \n breakpoints?

cocacrave
  • 2,453
  • 4
  • 18
  • 30

2 Answers2

4

You can use css white-space set to pre at element where .textContent is set

const multiLine = "This is line 1\nThis is line2\nThis is line3";

document.querySelector("div").textContent = multiLine;
div {
  white-space: pre;
}
<div></div>
guest271314
  • 1
  • 15
  • 104
  • 177
2

HTML doesn't interpret \n as a linebreak. You can use <br> instead.

A simple replace should do the job.

let multiLine = "This is line 1\nThis is line2\nThis is line3";
multiline = multiline.replace(/\n/g, '<br>');

Using a regular expression match to find all all matching properties. /\n/ is essential the same as \n. The g in /\n/g tells it to find all matching properties so it'll replace all matches and not just the first.

user3254198
  • 763
  • 6
  • 23
  • Thank you, I'll accept this as answer when it lets me – cocacrave Oct 04 '16 at 00:30
  • 1
    @user3254198 _"HTML doesn't interpret \n as a linebreak."_ If `white-space` is set to `pre` at element `style` attribute or `css` the `\n` should be rendered as a newline character. – guest271314 Oct 04 '16 at 00:34