在<code> tags in JS

时间:2015-11-12 18:45:36

标签: javascript regex replace

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.

2 个答案:

答案 0 :(得分:5)

如果您不在HTML标记上使用正则表达式,请在评论中提及 @ sterling-archer ,请查看 Using regular expressions to parse HTML: why not? ,而不是你可以在没有正则表达式的情况下做到这一点:

var list = document.getElementsByTagName("code")[0].textContent;
list = list.split('\n').join('</br>');

希望这有帮助。

答案 1 :(得分:2)

如果您仍想使用正则表达式,请尝试以下操作:

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;
})

它会将<code></code>之间的所有内容替换为\n,并将<br>替换为var fs = require('fs'); var stream = fs.createReadStream(path); stream.on('data',function(d){ //just pipe it to your writable stream (you can use the http response) });