简体   繁体   English

如何使用javascript中的正则表达式查找和替换特定HTML标签中的样式?

[英]How can i find and replace style in specific HTML tag with regex in javascript?

As I mentioned in the title, how can I change the contents of the style attribute within a given HTML tag?正如我在标题中提到的,如何在给定的 HTML 标签中更改 style 属性的内容?

for example:例如:

<table class="MsoTableLightShadingAccent1" border="1" cellspacing="0" cellpadding="0" style="margin-left: 45.9pt; border: none;">

I have got many html code like that.我有很多这样的html代码。 I wrote an RegEx like that in js:我在 js 中写了一个这样的 RegEx:

str = str.replace(/(<(?:table)[^<]*)(style="[^"]*")([^>]*>)/gi,'<table style="font-size:medium;">');

this can change table tag but actually i want to delete only "margin-left".这可以更改表格标签,但实际上我只想删除“左边距”。 How can i do that with js?我怎么能用js做到这一点?

Edit: I use summernote.编辑:我使用summernote。 When user paste a text, it triggers onPaste callback and i clean dirty tags and attributes.当用户粘贴文本时,它会触发 onPaste 回调并清理脏标签和属性。

You shouldn't parse HTML with regex, see this famous answer .您不应该使用正则表达式解析 HTML,请参阅这个著名的答案

JavaScript is perfectly capable of doing what you want though, something like this: JavaScript 完全有能力做你想做的事,就像这样:

<div id="someID" style="height: 50px; width: 50px; background-color: red; margin-left: 50px;"></div>

<button type="button" onclick="document.getElementById('someID').style.marginLeft = 0;">Click Me!</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM