I’m totally lost on how to write this regex. Basically what I need here is to wrap each line with a <p></p>
tag and every double new line with a <p><br /></p>
. So lets say I have the following string:
Hello WorldnnFoo BarnBas Baz
I need to write an output that would format it to the following:
<p>Hello World</p>
<p><br /></p>
<p>Foo Bar</p>
<p>Bas Baz</p>
Right now all I have is this but this doesn’t work. Its not wrapping single lines with <p>
tags
function textToHtml(text) {
text = text.replace(/nn/g, '<p><br /></p>');
return text;
}
---
textToHtml('Hello WorldnnFoo BarnBas Baz')
// 'Hello World<p><br /></p>Foo BarnBas Baz'
Any nudge in the right direction would be much appreciated
3
Answers
.+
will match one or more non-newline characters, so you could wrap the lines by adding the following as the first line of your function.$&
in the replacement string represents the whole match.The regex in this code is probably not entirely correct, but you want to use what are called "capture groups" with your regex to isolate the text you want to wrap.