How do I replace all line breaks in a string with <br /> tags?

How can I read the line break from a value with Javascript and replace all the line breaks with br tags?

Example:

A variable passed from PHP as below:

  "This is man.

     Man like dog.
     Man like to drink.

     Man is the king."

I would like my result to look something like this after the Javascript converts it:

  "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."

这将把所有返回转换为html。

str = str.replace(/(?:rn|r|n)/g, '<br>');

If your concern is just displaying linebreaks, you could do this with CSS.

HTML

<div class="white-space-pre">Some test
with linebreaks</div>

CSS

.white-space-pre {
    white-space: pre-wrap;
}

jsfiddle https://jsfiddle.net/yk1angkz/125/

Note : Pay attention to code formatting and indenting, since white-space: pre-wrap will display all whitespaces (except for the last newline after the text, see fiddle).


没有正则表达式:

str = str.split("n").join("<br />");
链接地址: http://www.djcxy.com/p/15680.html

上一篇: JLabel的Newline

下一篇: 如何用<br />标签替换字符串中的所有换行符?