2015-06-11 33 views
-69

我試圖從內聯樣式中只刪除一個屬性,float及其值。我想入手這款:如何使用正則表達式從內聯樣式中刪除樣式元素?

<div id="first_line_info" style="width:490px; float:right;"> </div> 

,使它像這樣:

<div id="first_line_info" style="width:490px"> </div> 

到目前爲止,我已經嘗試過這樣的代碼:

Regex noInlineStylePattern = new Regex("style=\"[^\"]*\"", RegexOptions.IgnoreCase); 
data = noInlineStylePattern.Replace(data, ""); 

這將刪除所有的內嵌樣式。我怎樣才能刪除浮球?

+0

是什麼你試圖刪除?只有'float:right;'的例子?任何'浮動'風格?所有樣式除了'width'? – AlliterativeAlice

+0

我想刪除所有浮標並保留寬度。我正在使用的文檔HTML中有多個浮點數。 – user3457760

+29

此外,你可能想看看[應該嗨,謝謝,標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines -and-問候被移除的從 - 職位) –

回答

12

這應除去所有浮:

data = Regex.Replace(data, @"(style=\"".*?)(float:\s*[^;\""]+;?)(.*?\"")", "$1$3", RegexOptions.IgnoreCase) 
9

此代碼刪除所有的風格元素屬性除了第一屬性

string test = @" <div id=""first_line_info"" style=""width:490px; float:right;""> </div>"; 

var result = Regex.Replace(test,"(style=\")(.*?;).*\"", new MatchEvaluator((m)=> 
      { 
       return m.Groups[1].Value + m.Groups[2].Value + @""""; 
      })); 

此代碼僅刪除從樣式元素浮動屬性

 var result2 = Regex.Replace(test, "(style=\".*?;).*(float:.*?;)\"", new MatchEvaluator((m) => 
    { 
     return m.Groups[1].Value + @""""; 
    })); 
1

我們可以實現同樣的與DOM操作:

var dom = document.createElement('div'); 
dom.innerHTML = `<div id="first_line_info" style="width:490px; float:right;"> </div> 
<div id="first_line_info1" style="width:490px;float:left;float:right"> </div> 
`; 
var elem = dom.getElementsByTagName('div'); 
var len=elem.length; 

for(var i=0;i<len;i++){ 
    elem[i].style.float = null; 
    //float removed 
} 

console.log(dom.innerHTML); 

從DOM操作加上正則表達式替換方法:
優勢:只需要匹配浮動沒有風格和浮動

var dom = document.createElement('div'); 
dom.innerHTML = `<div id="first_line_info" style="width:490px; float:right;"> </div> 
<div id="first_line_info1" style="width:490px; float:right;float:left"> </div> 
`; 
var elem = dom.getElementsByTagName('div'); 
var len=elem.length; 

for(var i=0;i<len;i++){  
    var style=elem[i].getAttribute('style'); 
    var regex = /(float:\w+;*)/g; 

    style = style.replace(regex, ""); 
    //float removed 

    elem[i].setAttribute('style',style);  
} 

console.log(dom.innerHTML);