2012-07-12 33 views
2

我有這個改變數的div到一個

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

它消除

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

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

太好了!

如果我有多個<div>

我怎樣才能讓

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

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

+4

用正則表達式來強制HTML只會導致疼痛,痛苦和心碎。你真的需要學習如何使用DOM操作來做這種事情。 – 2012-07-12 12:12:17

回答

0

你不能使用正則表達式來處理複雜的HTML操作!請see this question。 你可以使用jQuery操作DOM來達到相同的效果!

Please see this jsfiddle example for a possible alternative.

這是從小提琴jQuery代碼,假設requred的div是在與該ID toParse包裹DIV。

$('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); 
});​ 
+0

好的。你會如何建議使用jQuery? – 2012-07-12 12:24:32

+0

查看更新的帖子。我只是編寫代碼! – 2012-07-12 12:28:59

1

假設你已經從DOM選擇first元素...

var next = first.nextElementSibling; 

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

剛剛意識到,我們不是從DOM移除空的div。如果你想這樣做,你可以這樣做...

var next; 

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