Javascript 替换javascript中的换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5664503/
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
Replacing newline character in javascript
提问by Hyman
I am trying to replaces instances of \r
or \n
characters in my json object with <br />
for display on a website.
我正在尝试将json 对象中的实例\r
或\n
字符替换<br />
为用于在网站上显示。
I tried:
我试过:
myString = myString.replace("\r?\n", "<br />");
But this doesn't seem to do anything. When I replace the regex with something else (like "a"
for instance, the replace works as expected). Any ideas why this isn't working for the newline chars?
但这似乎没有任何作用。当我用其他东西替换正则表达式时("a"
例如,替换按预期工作)。任何想法为什么这不适用于换行符?
回答by Felipe
Try this:
尝试这个:
myString = myString.replace(/[\r\n]/g, "<br />");
Update:
As told by Pointy on the comment below, this would replace a squence of \r\n
with two <br />
, the correct regex should be:
更新:正如 Pointy 在下面的评论中所说,这将\r\n
用两个替换一个序列<br />
,正确的正则表达式应该是:
myString = myString.replace(/\r?\n/g, "<br />");
回答by Christian Pastor Cruz
CSS:
CSS:
white-space: pre-wrap;
Is a far more eficient method.
是一种更有效的方法。
回答by Vlad Khomich
try replace(/\r\n|\n/, '<br />')
尝试 replace(/\r\n|\n/, '<br />')
回答by Ricardo Ruwer
This worked for me:
这对我有用:
str = str.replace(/\n|\r\n|\r/g, '<br/>');
Using double slash
使用双斜线