如何使用JavaScript正则表达式删除标记

时间:2010-01-07 11:51:25

标签: javascript html regex parsing

我有一个包含HTML的JavaScript字符串,如下所示:

<div>
 <div class="a">
  content1
 </div>
 content 2
 <div class="a">
  <b>content 3</b>
 </div>
</div>

我希望删除class =“a”的div,但保留其内容。 在Python中我会使用类似的东西:

re.compile('<div class="a">(.*?)</div>', re.DOTALL).sub(r'\1', html)

使用Javascript正则表达式的等价物是什么?

3 个答案:

答案 0 :(得分:5)

为什么不使用正确的DOM方法?在jQuery的帮助下,这很简单:

var contents = $('<div><div class="a">content1</div>content 2<div class="a"><b>content 3</b></div></div>');

contents.find('.a').each(function() {
    $(this).replaceWith($(this).html());
});

答案 1 :(得分:2)

您可以使用JavaScript中的正则表达式实现它

var html = '<div> <div class="a"> content1 </div> <div class="a"> content1 </div> ... </div>';
var result = html.replace(/<div class="a">(.*?)<\/div>/g, function(a,s){return s;});
alert(result);

RegExp方法replace有两个参数 - 第一个是实际的,第二个是替换。由于没有一个但未知数量的替换,因此可以使用一个函数。

答案 2 :(得分:0)

如果您想在Javascript中执行此操作,我假设您在Web浏览器中运行它,并且您所引用的“javascript字符串”是以某种方式从DOM中提取的。 如果这两种情况都属实,那么我会说使用经过试验和测试的javascript库是个好主意,比如JQuery(还有其他的,但是我不使用它们,所以可以'真的评论) JQuery允许你像你描述的那样动态地进行DOM操作,相对容易......

$('div.a').each(function(){$(this).replaceWith($(this).html());});

JQuery绝对是支付红利的工具之一 - 失败的短学习曲线和大量的权力。

相关问题