简体   繁体   中英

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?

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. I wrote an RegEx like that in js:

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?

Edit: I use summernote. When user paste a text, it triggers onPaste callback and i clean dirty tags and attributes.

You shouldn't parse HTML with regex, see this famous answer .

JavaScript is perfectly capable of doing what you want though, something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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