Is there a way to make HTML properly treat \n
line breaks? Or I have to replace them with <br/>
?
This question is related to
html
You could use the <pre>
tag
<div class="text">_x000D_
<pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</div>
_x000D_
You can use CSS white-space
property for \n
. You can also preserve the tabs as in \t
.
For line break \n
:
white-space: pre-line;
For line break \n
and tabs \t
:
white-space: pre-wrap;
document.getElementById('just-line-break').innerHTML = 'Testing 1\nTesting 2\n\tNo tab';_x000D_
_x000D_
document.getElementById('line-break-and-tab').innerHTML = 'Testing 1\nTesting 2\n\tWith tab';
_x000D_
#just-line-break {_x000D_
white-space: pre-line;_x000D_
}_x000D_
_x000D_
#line-break-and-tab {_x000D_
white-space: pre-wrap;_x000D_
}
_x000D_
<div id="just-line-break"></div>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div id="line-break-and-tab"></div>
_x000D_
As per your question, it can be done by various ways: - For example you can use:
If you want to insert a new line in text area , you can try this:-
Line Feed and
Carriage return
<textarea>Hello Stackoverflow</textarea>
You can also
<pre>---</pre>
Preformatted text.
<pre>
This is Line1
This is Line2
This is Line3
</pre>
Or,you can use
<p>----</p>
Paragraph
<p>This is Line1</p>
<p>This is Line2</p>
<p>This is Line3</p>
Note: if you want to use
\n
you need to install a server like Xampp or Apache to support server side language
Using white-space: pre-line
allows you to input the text directly in the HTML with line breaks without having to use \n
If you use the innerText
property of the element via JavaScript on a non-pre element e.g. a <div>
, the \n
values will be replaced with <br>
in the DOM by default
innerText
: replaces \n
with <br>
innerHTML
, textContent
: require the use of styling white-space
It depends on how your applying the text, but there are a number of options
const node = document.createElement('div');
node.innerText = '\n Test \n One '
you can use <pre>
tag :
<div class="text">_x000D_
<pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</pre>_x000D_
</div>
_x000D_
Simple and linear:
<p> my phrase is this..<br>
the other line is this<br>
the end is this other phrase..
</p>
You should consider replacing your line breaks with <br/>
. In HTML a line break will only stand for new line in your code.
Alternatively you can use some other HTML markups like placing your lines in paragraphs:
<p>Sample line</p>
<p>Another line</p>
or other wrappers like for instance <div>sample</div>
with CSS attribute: display: block
.
You can also use <pre>
. The content of pre
will have its HTML styling ignored. In other words it will display pure HTML with normal \n
line breaks.
Source: Stackoverflow.com