Q:

Replace newlines with s within  tags in JS

I'm trying to replace all the new lines inside a <code></code> tags with <br>s, but my regex does not work. Here is the input text:
<p>
   <span class="dingus">►</span> for linebreak add 2 spaces at end
</p>
<code class="hl">
    Text in a code pre element
    is displayed in a fixed-width
    font, and it preserves
    both      spaces and
    line breaks
</code>
<p class="ar">
    <a href="/editing-help" target="_edithelp">formatting help »</a><br>
    <a href="/questions/how-to-ask">asking help »</a>
</p>

Regex:
var txt = str.replace(/<code[^>]*>((.|\n)*?)<\/code>/gm,function(match){
    return match.replace(/\n/gi, '<br>');
});

BTW, I know using a parser is the ideal solution, but still would like to know if it's possible with a simple regex for the example above.

A:

Better if you don't use regex on HTML tags lie @sterling-archer mentioned in comment, take a look at Using regular expressions to parse HTML: why not?, Instead you can do it without regex like :
var list = document.getElementsByTagName("code")[0].textContent;
list = list.split('\n').join('</br>');

Hope this helps.

A:

If you still want to use regular expressions, try this:
var str = 'other\nstuff\noutside<code class="hl">\nText in a pre element\nis displayed in a fixed-width\nfont, and it preserves\nboth      spaces and\nline breaks\n</code>';
var txt = str.replace(/(<code[^>]*>)([\S\s]*?)(<\/code>)/g, function(_, p1, p2, p3){
  return p1 + p2.replace(/\n/g, '<br>') + p3;
})

It takes the entire contents between <code> and </code> and replaces \n with <br> within it.

