I want to replace the multiple <br>
tags with single <br>
in a text.
我想在文本中用单个
替换多个
标签。
my text like,
我的文字像,
<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>
How i replace the multiple <br>
with single <br>
?.
我如何用单个
替换多个
?
2 个解决方案
#1
6
Try this
var str="<p>fhgfhgfhgfh</p><br><br><p>ghgfhfgh</p><br><br><p>";
var n=str.replace(/<br><br>/g,"<br>");
console.log(n);
Working DEMO
Edit: Above works for 2 br
tags, code below should take care of any number of br tags.
编辑:以上代码适用于2个br标签,下面的代码应该处理任意数量的br标签。
var n = str.replace(/(<br>)+/g, '<br>');
Working DEMO
where /.../
denotes a regular expression, (<br>)
denotes <br>
tag, and +
denotes one or more occurrence of the previous expression and finally g
is for global replacement.
其中/.../表示正则表达式,(
)表示
标签,+表示前一个表达式的一个或多个出现,最后g表示全局替换。
#2
2
This should do the trick:
这应该是诀窍:
str.replace(/(?:<br>){2,}/g, '<br>')
Or, if they can be on different lines:
或者,如果他们可以在不同的行:
str.replace(/(?:<br>\s*){2,}/g, '<br>')
#1
6
Try this
var str="<p>fhgfhgfhgfh</p><br><br><p>ghgfhfgh</p><br><br><p>";
var n=str.replace(/<br><br>/g,"<br>");
console.log(n);
Working DEMO
Edit: Above works for 2 br
tags, code below should take care of any number of br tags.
编辑:以上代码适用于2个br标签,下面的代码应该处理任意数量的br标签。
var n = str.replace(/(<br>)+/g, '<br>');
Working DEMO
where /.../
denotes a regular expression, (<br>)
denotes <br>
tag, and +
denotes one or more occurrence of the previous expression and finally g
is for global replacement.
其中/.../表示正则表达式,(
)表示
标签,+表示前一个表达式的一个或多个出现,最后g表示全局替换。
#2
2
This should do the trick:
这应该是诀窍:
str.replace(/(?:<br>){2,}/g, '<br>')
Or, if they can be on different lines:
或者,如果他们可以在不同的行:
str.replace(/(?:<br>\s*){2,}/g, '<br>')