简体   繁体   中英

Replace newlines with <br>s within <code> 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM