Regex to match single new line. Regex to match double new line

All JavaScript environments compliant with ECMAScript 2018 support lookbehind.

Thus, you may use

(?<!\n)\r?\n(?!\r?\n)

to match a single CRLF or LF libne break sequence. If you need to match two line breaks, wrap the \r?\n consuming pattern part within a group and set a quantifier to it: (?<!\n)(?:\r?\n){2}(?!\r?\n) matches a double line break sequece.

Details:

  • (?<!\n) - a negative lookbehind that fails the match if there is an LF char immediately to the left of the current location
  • \r?\n - an optional CR and then an LF char
  • (?!\r?\n) - a negative lookahead that fails the match if there is an optional CR and then an LF char immediately to the right of the current location.

See the JavaScript demo showing how to replace in-paragraph line break sequences, i.e. those single line break sequences:

const text = "This\nis\nparagraph\none\n\nThis is the\nsecond\nparagraph";
console.log( text.replace(/(?<!\n)\r?\n(?!\r?\n)/g, "<br />") );

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.