javascript,用\r\n 替换\n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16165215/
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
javascript, replace \n with \r\n
提问by Ilya
I need to replace all \nwith \r\n, but only if \nhasn't already \rpreviosly.
i.e.Hello\nGreat\nWorld-> Hello\r\nGreat\r\nWorldHello\r\nGreat\r\nWorld-> Hello\r\nGreat\r\nWorld.
我需要将 all 替换\n为\r\n,但前提是之前\n尚未替换\r。
即Hello\nGreat\nWorld-> Hello\r\nGreat\r\nWorldHello\r\nGreat\r\nWorld-> Hello\r\nGreat\r\nWorld。
In Java i can do it in next way
在 Java 中,我可以用下一种方式来完成
"Hello\nGreat\nWorld".replaceAll("(?<!\r)\n", "\r\n");
But (?<!X)construct is absent in JS.
Any ideas, how can I do it in JS?
但是(?<!X)在 JS 中没有构造。
任何想法,我怎样才能在JS中做到这一点?
回答by Jon
Simply make the \ran optional part of the match, then you can replace with impunity:
只需\r将匹配的可选部分设置为可选部分,然后您就可以不受惩罚地替换:
"Hello\r\nWorld\n".replace(/\r?\n/g, "\r\n")
回答by RichieHindle
str.replace('\r\n', '\n').replace('\n', '\r\n')

