2017-05-31 51 views
2

我試圖在javascript或jQuery中從字符串(而不是對象)中刪除所有樣式屬性。從字符串中刪除樣式屬性

var html = "<p style="color:red">my text</p>"; 

,我想獲得該

<p>my text</p> 

是否有可能做到這一點,而無需調用,我們可以調用的對象(如removeAttr)的功能是什麼?

謝謝

+2

爲什麼你要做到這一點使用字符串操作,而不是DOM方法能避免使用正則表達式解析HTML字符串的邊緣案件? –

+0

因爲我把字符串放在一個對象中時從來沒有得到完整的html – user

+0

你可以在* simple * html字符串上使用正則表達式,但是大量嵌套的html對於正則表達式不是一個好的用例。所以這取決於你的html字符串是否像單個節點一樣? – James

回答

1

如果您不想使用JavaScript或jQuery對象,您是否嘗試過使用正則表達式?

This answer到上一個問題顯示了一個php版本,可以使用replace函數來適應JavaScript。

+2

這對我有用.replace(/ style =「[^」] *「/ g,」「) – user

0

看看這是否有幫助。

$("button").click(function() { 
 
    $("p").removeAttr("style"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<p style="color:red">my text</p> 
 

 
<button>Remove the style attribute from all p elements</button>