Javascript 在javascript中用<br>替换\n和用<p>替换\r\n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2390038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:05:30  来源:igfitidea点击:

Replace \n with <br> and \r\n with <p> in javascript

javascriptstring

提问by rich

I need JS that will remove any HTML tags, and then replace newlines with </p><p>and line breaks with <br/>. The string value is coming from a textarea and I understand Linux, Mac and Windows all format newlines differently so I need to take that into account. Thanks!

我需要 JS 来删除任何 HTML 标签,然后</p><p><br/>. 字符串值来自 textarea,我了解 Linux、Mac 和 Windows 的换行格式都不同,所以我需要考虑到这一点。谢谢!

回答by Joel

\n and \r\n are equivalent. Linux uses the former, Windows uses the latter.

\n 和 \r\n 是等价的。Linux 使用前者,Windows 使用后者。

What you want to do is replace all cases of \n\n and \r\n\r\n with <p></p>and case of simply \n or \r\n with <br />

您想要做的是将 \n\n 和 \r\n\r\n 的所有情况替换<p></p>为简单的 \n 或 \r\n 的情况<br />

result = "<p>" + text + "</p>";
result = result.replace(/\r\n\r\n/g, "</p><p>").replace(/\n\n/g, "</p><p>");
result = result.replace(/\r\n/g, "<br />").replace(/\n/g, "<br />");

This assumes there is no html in your text.

这假设您的文本中没有 html。

回答by Alex Polkhovsky

I think

我认为

value.replace(/\n\n/g, "</p><p>");
value.replace(/\n/g, "<br/>");

will do the trick.

会做的伎俩。