Since JavaScript does not support lookbehind statements, you need to match one extra character in front of your \ n`s and remember to process it later (i.e., restore it if you use regular expression matching to change the original string).
(^|[^\n])\n(?!\n)
matches one new line plus the previous character and
(^|[^\n])\n{2}(?!\n)
matches two newlines plus the previous character.
So, if you want to replace one \n with <br /> , for example, you need to do
result = subject.replace(/(^|[^\n])\n(?!\n)/g, "$1<br />");
For \n\n this is
result = subject.replace(/(^|[^\n])\n{2}(?!\n)/g, "$1<br />");
Look at regex101
Explanation:
(
source share