11

I need to replace all \n with \r\n, but only if \n hasn't already \r previosly.
i.e.
Hello\nGreat\nWorld -> Hello\r\nGreat\r\nWorld
Hello\r\nGreat\r\nWorld -> Hello\r\nGreat\r\nWorld.

In Java i can do it in next way

"Hello\nGreat\nWorld".replaceAll("(?<!\r)\n", "\r\n");  

But (?<!X) construct is absent in JS.
Any ideas, how can I do it in JS?

4

2 回答 2

36

Simply make the \r an optional part of the match, then you can replace with impunity:

"Hello\r\nWorld\n".replace(/\r?\n/g, "\r\n")
于 2013-04-23T09:05:38.823 回答
5
str.replace('\r\n', '\n').replace('\n', '\r\n')
于 2013-04-23T09:06:06.167 回答