简体   繁体   English

在javascript中替换换行符

[英]Replacing newline character in javascript

I am trying to replaces instances of \\r or \\n characters in my json object with <br /> for display on a website. 我试图取代的情况下, \\r\\n与字符的json对象<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). 当我用其他东西替换正则表达式时(例如"a" ,替换按预期工作)。 Any ideas why this isn't working for the newline chars? 任何想法为什么这不适用于换行符?

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 />");

This worked for me: 这对我有用:

str = str.replace(/\\n|\\r\\n|\\r/g, '<br/>');

Using double slash 使用双斜线

CSS: CSS:

 white-space: pre-wrap;

Is a far more eficient method. 是一种更有效的方法。

尝试replace(/\\r\\n|\\n/, '<br />')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM