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?

Ilya
  • 28,466
  • 18
  • 106
  • 153

2 Answers2

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")
Jon
  • 413,451
  • 75
  • 717
  • 787
  • 1
    @Jack: I saw all that and was currently thinking "that happens to me all the time too" :) – Jon Apr 23 '13 at 09:07
5
str.replace('\r\n', '\n').replace('\n', '\r\n')
RichieHindle
  • 258,929
  • 46
  • 350
  • 392