views:

208

answers:

3

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?

+5  A: 

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());
});
Tatu Ulmanen
+2  A: 

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.

Andris
+1 didn't know you can pass a function to replace
Tatu Ulmanen
There's a lot of unknown and undervalued features in JavaScript - Flanagan's JavaScript Reference was a real eye-opener for me in this area.
Andris
A: 

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.

belugabob
For my particular use case manipulating the DOM is too slow
Plumo
According to your comments to other posts, you're generating the markup on the server side, but want to have dynamic client-side functionality- as far as I know, this can't be done without manipulating the DOM. Am I missing something?
belugabob
Yes, I am sending this parsed html back to the server with unimportant tags removed for faster upload
Plumo
Ok - that explains the lack of DOM manipulation. It does look like the method suggested by Andris is your best bet. I would, however, be interested in seeing more information about the data being passed around, as I can't help thinking that the whole thing is a bit of a bodge (Although this may be forced upon you by the client and/or legacy code)
belugabob