如何用<br />标记替换字符串中的所有换行符?

如何使用JavaScript从值读取换行符并将所有换行符替换为<br />标签?

例:

从PHP传递的变量如下:

  "This is man.

     Man like dog.
     Man like to drink.

     Man is the king."

我希望我的结果在JavaScript转换后看起来像这样:

  "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
A小卤蛋Pro2020/03/12 16:19:55

尝试

let s=`This is man.

     Man like dog.
     Man like to drink.

     Man is the king.`;
     
msg.innerHTML = s.replace(/\n/g,"<br />");
<div id="msg"></div>

LEYPro达蒙2020/03/12 16:19:55

如果您从PHP发送变量,则可以在发送之前通过以下方式获取它:

$string=nl2br($string);
小宇宙泡芙2020/03/12 16:19:54

如果您只想显示换行符,则可以使用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).

米亚神无2020/03/12 16:19:54

没有正则表达式:

str = str.split("\n").join("<br />");