Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's how Steve Levithan's first <a href="http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript" rel="nofollow noreferrer">lookbehind-alternative</a> can be applied to your problem:</p> <pre><code>var output = s.replace(/(&lt;pre&gt;[\s\S]*?&lt;\/pre&gt;)|\n/g, function($0, $1){ return $1 ? $1 : '&lt;p/&gt;'; }); </code></pre> <p>When it reaches a <code>&lt;pre&gt;</code> element, it captures the whole thing and plugs it right back into the output. It never really sees the newlines inside the element, just gobbles them up along with all other content. Thus, when the <code>\n</code> in the regex <em>does</em> match a newline, you know it's not inside a <code>&lt;pre&gt;</code> element, and should be replaced with a <code>&lt;p/&gt;</code>. </p> <p>But don't make the mistake of regarding this technique as a hack or a workaround; I would recommend this approach even if lookbehinds <em>were</em> available. With the lookaround approach, the regex has to examine every single newline and apply the lookarounds each time to see if it should be replaced. That's a lot of unnecessary work it has to do, plus the regex is a lot more complicated and less maintainable.</p> <p>As always when using regexes on HTML, I'm ignoring a lot of factors that can affect the result, like SGML comments, CDATA sections, angle brackets in attribute values, etc. You'll have to determine which among those factors you have to deal with in your case, and which ones you can ignore. When it comes to processing HTML with regexes, there's no such thing as a general solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload