在javascript中替换多个<br>替换为单个<br>?

Nav*_*een 3 html javascript regex

我想在文本<br>中用单个替换多个标签<br>.

我的文字就像,

<p>fhgfhgfhgfh</p>
<br><br>
<p>ghgfhfgh</p>
<br><br>
<p>fghfghfgh</p>
<br><br>
<p>fghfghfgh</p>
<br><br>
<p>fghfgh</p>
<br><br>
Run Code Online (Sandbox Code Playgroud)

我如何<br>用单个替换倍数<br>

Gur*_*ngh 6

试试这个

var str="<p>fhgfhgfhgfh</p><br><br><p>ghgfhfgh</p><br><br><p>";

var n=str.replace(/<br><br>/g,"<br>");

console.log(n);
Run Code Online (Sandbox Code Playgroud)

工作演示

编辑:以上br代码适用于2个标签,下面的代码应该处理任意数量的br标签.

var n = str.replace(/(<br>)+/g, '<br>');
Run Code Online (Sandbox Code Playgroud)

工作演示

where /.../表示正则表达式,(<br>)表示<br>标记,+表示前一个表达式的一次或多次出现,最后g用于全局替换.


Ja͢*_*͢ck 5

这应该可以解决问题:

str.replace(/(?:<br>){2,}/g, '<br>')
Run Code Online (Sandbox Code Playgroud)

或者,如果它们可以位于不同的行上:

str.replace(/(?:<br>\s*){2,}/g, '<br>')
Run Code Online (Sandbox Code Playgroud)