単一の改行文字 ( \n) に一致する正規表現を構築しようとしています。
同様に、またはなど\n\nの長い改行文字の一部ではない二重改行 ( ) に一致する別の正規表現が必要です。\n\n\n\n\n\n\n\n\n
\n(?!\n)一致し\n\n(?!\n)すぎます (より長い一連の改行の最後の改行に一致します)。代わりに何ができますか?
単一の改行文字 ( \n) に一致する正規表現を構築しようとしています。
同様に、またはなど\n\nの長い改行文字の一部ではない二重改行 ( ) に一致する別の正規表現が必要です。\n\n\n\n\n\n\n\n\n
\n(?!\n)一致し\n\n(?!\n)すぎます (より長い一連の改行の最後の改行に一致します)。代わりに何ができますか?
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.