2

I have this

str = testString.replace(/<div style="(.*?)">(.*?)<\/div><div style="\1">/g, '<div style="$1">$2<br>');

It removes

<div style="text-align: right;">text1</div>
<div style="text-align: right;">text2</div>

into

<div style="text-align: right;">
    text1<br>text2
</div>

Great!

What if i have multiple <div>'s?

How can i make

<div style="text-align: right;">text1</div>
<div style="text-align: right;">text2</div>
<div style="text-align: right;">text3</div>
<div style="text-align: right;">text4</div> 

into

<div style="text-align: right;">
    text1<br>text2<br>text3<br>text4
</div>

?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Morten Hauberg
  • 531
  • 1
  • 5
  • 12
  • 4
    mangling html with regexs is only going to lead to pain, misery, and heartbreak. you really need to learn how to use DOM manipulation to do this sort of thing. – Marc B Jul 12 '12 at 12:12

2 Answers2

1

Assuming you've already selected the first element from the DOM...

var next = first.nextElementSibling;

while (next && next.nodeName.toUpperCase() === "DIV") {
    first.appendChild(document.createElement('br'))
    first.appendChild(next.firstChild)
    next = next.nextElementSibling
}

Just realized that we're not removing the empty divs from the DOM. If you wanted that, you can do this...

var next;

while ((next = first.nextElementSibling) && next.nodeName.toUpperCase() === "DIV") {
    first.appendChild(document.createElement('br'))
    first.appendChild(next.firstChild)
    next.parentNode.removeChild(next);
}
0

Thou cannot use regex for complex HTML manipulations! Please see this question. You could manipulate the DOM using jQuery to achieve the same result!

Please see this jsfiddle example for a possible alternative.

This is the jQuery code from the fiddle, assuming the requred divs are in a wrapping div with the id toParse.

$('body').ready(function() {

var template = $('#toParse div').first().clone();

var result = "";
$('#toParse div').each(function(index, element) {
    result += $(element).html();
    result += "<br/>";
});

// you can add some extra code here to remove that 
// extra final <br/>

$('#toParse').html($(template).html(result));
console.log(result); 
});​
Community
  • 1
  • 1
Andrei Bârsan
  • 3,473
  • 2
  • 22
  • 46