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:
repile('<div class="a">(.*?)</div>', re.DOTALL).sub(r'\1', html)
What is the equivalent using 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.pile('<div class="a">(.*?)</div>', re.DOTALL).sub(r'\1', html)
What is the equivalent using Javascript regular expressions?
Share Improve this question asked Jan 7, 2010 at 11:51 hojuhoju 29.5k40 gold badges137 silver badges178 bronze badges 4- 5 Here we go again... HTML and regex is an invitation to doom. (stackoverflow./questions/1732348/…) – Dominic Rodger Commented Jan 7, 2010 at 11:56
- Not in this case however, because the HTML is generated server side by me – hoju Commented Jan 7, 2010 at 12:09
- Why don't you generate it without the tags you don't want? – Quentin Commented Jan 7, 2010 at 12:16
- Because this is for some dynamic client-side functionality – hoju Commented Jan 7, 2010 at 12:24
3 Answers
Reset to default 5Why 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 ment) 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.