在JS中的<code>标记内用换句号替换换行符

Sij*_*Din 0 javascript regex replace

我试图<code></code><br>s 替换标签内的所有新行,但我的正则表达式不起作用.这是输入文本:

<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>
Run Code Online (Sandbox Code Playgroud)

正则表达式:

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

顺便说一句,我知道使用解析器是理想的解决方案,但仍然想知道上面的例子是否可以使用简单的正则表达式.

Zak*_*rki 5

如果你不在HTML标签上使用正则表达式,那么更好的是评论中提到的@ sterling-archer,看看使用正则表达式来解析HTML:为什么不呢?,相反,你可以没有像正则表达式那样做:

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

希望这可以帮助.