我试图在javascript或jQuery中从字符串(而不是对象)中删除所有样式属性。从字符串中删除样式属性
例
var html = "<p style="color:red">my text</p>";
,我想获得该
<p>my text</p>
是否有可能做到这一点,而无需调用,我们可以调用的对象(如removeAttr)的功能是什么?
谢谢
我试图在javascript或jQuery中从字符串(而不是对象)中删除所有样式属性。从字符串中删除样式属性
例
var html = "<p style="color:red">my text</p>";
,我想获得该
<p>my text</p>
是否有可能做到这一点,而无需调用,我们可以调用的对象(如removeAttr)的功能是什么?
谢谢
如果您不想使用JavaScript或jQuery对象,您是否尝试过使用正则表达式?
This answer到上一个问题显示了一个php版本,可以使用replace
函数来适应JavaScript。
这对我有用.replace(/ style =“[^”] *“/ g,”“) – user
看看这是否有帮助。
$("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>
为什么你要做到这一点使用字符串操作,而不是DOM方法能避免使用正则表达式解析HTML字符串的边缘案件? –
因为我把字符串放在一个对象中时从来没有得到完整的html – user
你可以在* simple * html字符串上使用正则表达式,但是大量嵌套的html对于正则表达式不是一个好的用例。所以这取决于你的html字符串是否像单个节点一样? – James