Since JavaScript doesn't support lookbehind assertions, you need to match one additional character before your \
n`s and remember to deal with it later (i.e., restore it if you use the regex match to modify the original string).
(^|[^\n])\n(?!\n)
matches a single newline plus the preceding character, and
(^|[^\n])\n{2}(?!\n)
matches double newlines plus the preceding character.
So if you want to replace a single \n
with a <br />
, for example, you have to do
result = subject.replace(/(^|[^\n])\n(?!\n)/g, "$1<br />");
For \n\n
, it's
result = subject.replace(/(^|[^\n])\n{2}(?!\n)/g, "$1<br />");
See it on regex101
Explanation:
( # Match and capture in group number 1:
^ # Either the start of the string
| # or
[^\n] # any character except newline.
) # End of group 1. This submatch will be saved in $1.
\n{2} # Now match two newlines.
(?!\n) # Assert that the next character is not a newline.