如何在 JavaScript 中找到换行符并替换为 <br> 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13532761/
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
How do I find line breaks and replace with <br> elements in JavaScript?
提问by user1260310
I am trying to find and replace line breaks in text using javascript.
我正在尝试使用 javascript 查找和替换文本中的换行符。
The following works. It replaces the character a with the character z.
以下作品。它将字符 a 替换为字符 z。
var text = "aasdfasdf";
text= text.replace(/a/g,"z");
alert(text);
The following based on other posts on this and other message boards does not. Basically the javascript does not fire:
以下基于此和其他留言板上的其他帖子没有。基本上javascript不会触发:
var text = "aasdfasdf";
text= text.replace(/\n/g,"z");
alert(text);
...Here is one of many posts that suggests it should work.
...这是建议它应该工作的许多帖子之一。
JavaScript: How to add line breaks to an HTML textarea?
JavaScript:如何向 HTML 文本区域添加换行符?
and by the way following does not work for me in Firefox either:
顺便说一下,以下内容在 Firefox 中也不适用于我:
text = text.replace(/\n\r?/g, '<br />'); or
text = text.replace("\n", '<br />');
Note: I realize there are no line breaks in the text variable..I am just using a simple string for testing purposes.
注意:我意识到文本变量中没有换行符......我只是使用一个简单的字符串进行测试。
Can anyone see what could be wrong or show me a way to do this that actually works.
任何人都可以看到可能出了什么问题或向我展示了一种实际可行的方法。
Thanks.
谢谢。
回答by T.J. Crowder
I'd cover my bets by handling \r\n
(the sequence), and then handling \r
and \n
through a character class, like this:
我会通过处理\r\n
(序列),然后处理\r
和\n
通过字符类来覆盖我的赌注,如下所示:
text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');
The first replace turns the sequence \r\n
into <br />
. The second replace replaces any \r
or \n
characters found on their own with the string.
第一次替换将序列\r\n
变为<br />
. 第二个替换用字符串替换自己找到的任何\r
或\n
字符。
More on regular expressions in JavaScript here.
更多关于 JavaScript 中的正则表达式在这里。
回答by Bruno
To handle windows new line characters try
要处理 Windows 换行符,请尝试
text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');
回答by austincheney
ECMAScript normalizes line breaks in strings to "\n\r" and the DOM normalizes line breaks in strings to "\n". Both of those OS agnostic which these formats:
ECMAScript 将字符串中的换行符规范化为“\n\r”,DOM 将字符串中的换行符规范化为“\n”。这些格式与操作系统无关:
- Windows - CRLF
- Unix - LF
- Old Mac - CR
- 视窗 - CRLF
- Unix - LF
- 旧 Mac - CR
The right way to accomplish this task depends on how you are receiving the string and how you are writing it out.
完成此任务的正确方法取决于您如何接收字符串以及如何将其写出。
回答by WSkinner
Another solution for both types of line endings
两种类型的行尾的另一种解决方案
str.replace(new RegExp('\r?\n','g'), '<br />');