In Regex perspective, to make the first <p>
become an exception, you must identify a pattern which makes the first <p>
fails. For example, if text before first <p>
is abcxyz
, that is, abcxyz<p>
, then you search every <p>
which is not preceded by abcxyz
, so that the first <p>
doesn't match. Using regex, it becomes: (?<!abcxyz)<p>
To make the last </p>
become an exception, you must identify a pattern which makes the last </p>
fails. For example, if text after last </p>
is abcxyz
, that is, </p>abcxyz
, then you search every </p>
which is not followed by abcxyz
, so that the last </p>
doesn't match. Using regex, it becomes: </p>(?!abcxyz)
Although JavaScript support positive and negative look-ahead, unfortunately, JavaScript regex doesn't support neither positive nor negative look-behind. Indeed, there are some dirty tricks to mimic look-behind in JavaScript, however, not all look-behind construct can be mimicked.
Thus, if possible, try to identify a pattern which makes the first <p>
fails, but use negative look-ahead.
To replace the first <p>
and the last </p>
with nothing, you can inverse the logic we use above, and you have to do this in separate step.
To replace <br>
, <br />
, <br/>
with \n
, search for: <br\s*\/?>
, and replace with \n
.