0

I have a string that has line breaks at the end of each line like the one I have below:

1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678
1234567
123456
12345
1234
123
12
1

This is from a string variable which I want to set to a paragraph tag in HTML. I tried using the innerHTML method but it only printed my results without the line breaks.

Any idea on how I can accomplish this task?

2 Answers 2

1

You could replace all the newlines with <br>s:

const str = `1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678
1234567
123456
12345
1234
123
12
1`;
document.querySelector('p').innerHTML = str.replace(/\n/g, '<br>');
<p></p>

Sign up to request clarification or add additional context in comments.

Comments

1

You can set the paragraph's white-space CSS property to pre, pre-wrap, or pre-line. All will preserve line breaks.

document.querySelector('p').innerHTML = `1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678
1234567
123456
12345
1234
123
12
1`;
p {
  white-space: pre;
}
<p></p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.