Reputation: 5844
I am converting html
to markdown
and vice versa.
When I convert html
having multiple blank lines then I am getting following markdown.
"First Line↵↵ (Shouldn't be replaced)
No Blank Line above this↵↵ (Shouldn't be replaced)
↵↵ (to be replaced)
↵↵ (to be replaced)
There are two empty new lines above this.↵↵ (Shouldn't be replaced)
No empty line above this."
Now If I use markdown.replace(/\n\n/g, '<br>')
then it replaces the \n\n
where it is not supposed to like in First Line
.
I am not able to make a regex which can do this. I've also tried regex with \b
but it doesn't worked for me.
Any help would be appreciated.
I've added space in markdown string for illustrative purpose. In general I get a complete string like this:"
"First Line↵↵No Blank Line above this↵↵↵↵↵↵There are two empty new lines above this.↵↵No empty line above this."
Upvotes: 1
Views: 154
Reputation: 627100
You may match a double LF char and then a sequence of 1 or more occurrences of the double LF char, and only replace those that come after the first \n\n
.
.replace(/\n\n((?:\n\n)+)/g, function (_,x) { return "\n\n" + x.replace(/\n\n/g, '<br>'); })
or, to support ES5 (if needed)
.replace(/\n\n((?:\n\n)+)/g, function (_,x) { return "\n\n" + x.replace(/\n\n/g, '<br>'); })
or, if you target ECMAScript2018+:
.replace(/(?<=\n\n)\n\n/g, '<br>')
Details
\n\n
- two newlines((?:\n\n)+)
- Capturing group 1 matching one or more (+
) occurrences of a \n\n
char sequence (note it is made a sequence by use of a non-capturing group, (?:...)
, where the \n\n
are placed)In the replacement, a callback method is used. It accepts a whole match (_
) and Group 1 value (x
). The return value is "\n\n"
plus the result of x.replace(/\n\n/g, '<br>')
, all \n\n
occurrences are replaced with <br>
.
The /(?<=\n\n)\n\n/g
pattern matches all occurrences (g
) of \n\n
that are immediately preceded with \n\n
(see the positive lookbehind (?<=\n\n)
).
JS demo:
var markdown = "First Line\n\nNo Blank Line above this\n\n\n\n\n\nThere are two empty new lines above this.\n\nNo empty line above this."
console.log(markdown.replace(/\n\n((?:\n\n)+)/g, function (_,x) { return "\n\n" + x.replace(/\n\n/g, '<br>'); }));
Upvotes: 1