简体   繁体   English

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

[英]how to remove tags with JavaScript regular expressions

I have a JavaScript string containing HTML like this: 我有一个包含HTML的JavaScript字符串,如下所示:

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

and I want to remove the div's of class="a" but leave their content. 我想删除class =“ a”的div,但保留其内容。 In Python I would use something like: 在Python中,我会使用类似:

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

What is the equivalent using Javascript regular expressions? 使用Javascript正则表达式的等效项是什么?

Why don't you use proper DOM methods? 您为什么不使用正确的DOM方法? With a little help from jQuery, that's dead simple: 在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());
});

You can achieve it with regular expressions in JavaScript 您可以使用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 method replace takes two parameters - first one is the actual re and the second one is the replacement. RegExp方法的replace具有两个参数-第一个参数是实际值,第二个参数是替换值。 Since there is not one but unknown number of replacements then a function can be used. 由于没有一个但未知的替换次数,因此可以使用一种功能。

If you want to do this in Javascript, I'm presuming that you are running it in a web browser, and that the 'javascript string' that you refer to was extracted from the DOM in some way. 如果要使用Javascript执行此操作,则假定您正在Web浏览器中运行它,并且您所引用的“ javascript字符串”是以某种方式从DOM中提取的。 If both of these case are true, then I'd say that it would be a good idea to use a tried and tested javascript library, such as JQuery (There are others out there, but I don't use them, so can't really comment) JQuery allows you to do on-the-fly DOM manipulations like you describe, with relative ease... 如果这两种情况都是正确的,那么我想说,使用一个久经考验的javascript库(例如JQuery)是一个好主意(还有其他方法,但是我不使用它们,所以可以) t真正的评论)JQuery允许您相对轻松地进行即时的DOM操作...

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

JQuery is definitely one of those tools that pays dividends - a failry short learning curve and a whole lot of power. jQuery绝对是那些能带来回报的工具之一-短短的学习曲线和强大的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM