Javascript regexp 替换所有 <br />

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5825825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:04:58  来源:igfitidea点击:

Javascript regexp replace all <br />'s

javascriptregex

提问by Tom Gullen

I'm trying to replace any <br />tags that appear AFTER a </h2>tag. This is what I have so far:

我正在尝试替换<br />出现在</h2>标签之后的任何标签。这是我到目前为止:

Text = Text.replace(new RegExp("</h2>(\<br \/\>.+)(.+?)", "g"), '</h2>');

It doesn't seem to work, can anyone help? (No matches are being found).

它似乎不起作用,有人可以帮忙吗?(没有找到匹配项)。

Test case:

测试用例:

<h2>Testing</h2><br /><br /><br />Text

To:

到:

<h2>Testing</h2>Text

回答by mVChr

This is simpler than you're thinking it out to be:

这比您想象的要简单:

Text = Text.replace(new RegExp("</h2>(\<br \/\>)*", "g"), "</h2>");

回答by serby

This would do what you are asking:

这将满足您的要求:

Text = Text.replace(new RegExp("</h2>(<br />)*", "g"), '</h2>');

回答by mu is too short

If you have jQuery kicking around then you can do this safely without regular expressions:

如果你有 jQuery,那么你可以在没有正则表达式的情况下安全地做到这一点:

var $dirty = $('<div>').append('<p>Where is<br>pancakes</p><h2>house?</h2><br><br>');
$dirty.find('h2 ~ br').remove();
var clean = $dirty.html();
// clean is now "<p>Where is<br>pancakes</p><h2>house?</h2>"

This will also insulate against the differences between <br>, <br/>, <br />, <BR>, etc.

这也将针对隔离之间的差异<br><br/><br /><BR>,等。

回答by serby

You can also make this a little nicer? using the shorthand regex syntax

你也可以让这个更好一点?使用简写正则表达式语法

Text = Text.replace(/<\/h2>(<br\s*\/>)*/g, '</h2>');