开发者

how to remove tags with JavaScript regular expressions

I have a JavaScript string containing HTML like this:

<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. In Python I would use something like:

re.compile('开发者_运维知识库<div class="a">(.*?)</div>', re.DOTALL).sub(r'\1', html)

What is the equivalent using Javascript regular expressions?


Why don't you use proper DOM methods? With a little help from jQuery, that's dead simple:

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

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. 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. 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...

$('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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜