JavaScript 用 <br /> 替换 \n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5076466/
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 15:32:30  来源:igfitidea点击:

JavaScript replace \n with <br />

javascriptregexreplace

提问by Tom Gullen

var messagetoSend = $.trim(document.getElementById("msgText").value);
messagetoSend = messagetoSend.replace("\n", "<br />");
alert(messagetoSend);

Given input:

给定输入:

Line 1


Line 2




Line 3

This alerts:

这提醒:

Line 1<br />


Line 2




Line 3

When I expect it to alert:

当我希望它发出警报时:

Line 1<br /><br /><br />Line 2<br /><br /><br /><br /><br />Line 3

回答by mplungjan

You need the /g for global matching

您需要 /g 进行全局匹配

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

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

This works for me for \n- see this answerif you might have \r\n

这对我有用\n-如果您有,请参阅此答案\r\n

NOTE:The dupeis the most complete answer for any combination of \r\n, \ror \n

注意:dupe\r\n,\r\n

var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");
console.log(messagetoSend);
<textarea id="x" rows="9">
    Line 1
    
    
    Line 2
    
    
    
    
    Line 3
</textarea>

UPDATE

更新

It seems some visitors of this question have text with the breaklines escaped as

似乎这个问题的一些访问者的文本与断裂线转义为

some text\r\nover more than one line"

一些文本\r\n超过一行”

In that case you need to escape the slashes:

在这种情况下,您需要转义斜线:

replace(/\\r\\n/g, "<br />");

replace(/\\r\\n/g, "<br />");

NOTE: All browsers will ignore \rin a string when rendering.

注意:所有浏览器\r在渲染时都会忽略一个字符串。

回答by WSkinner

Handles either type of line break

处理任一类型的换行符

str.replace(new RegExp('\r?\n','g'), '<br />');

回答by jAndy

Use a regular expression for .replace().:

.replace().使用正则表达式:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

如果这些换行符是由 windows 编码产生的,您还必须替换carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");