How can i remove all inline style properties which starts with 'font-'?
INPUT
<div style="font-size:3px;color:red;">
<p style="font-size:5px;"></p>
</div>
OUTPUT
<div style="color:red;">
<p style=""></p>
</div>
How can i remove all inline style properties which starts with 'font-'?
INPUT
<div style="font-size:3px;color:red;">
<p style="font-size:5px;"></p>
</div>
OUTPUT
<div style="color:red;">
<p style=""></p>
</div>
Share
Improve this question
edited Sep 25, 2014 at 9:36
Array out of bound
asked Sep 24, 2014 at 7:39
Array out of boundArray out of bound
1,1337 silver badges24 bronze badges
2
-
replace
font-[^;]+;
with''
. – hjpotter92 Commented Sep 24, 2014 at 7:41 -
@hjpotter92: can leak into document text.
"<em>font-related</em> decisions should be left to the designers; they know best."
→"<em> they know best."
There is no good way to do this with regular expressions only. – Amadan Commented Sep 24, 2014 at 7:49
4 Answers
Reset to default 5While that HtmlAgilityPack answer looks impressive, try this much simpler code:
var elements = document.querySelectorAll("[style*='font-']"),
l = elements.length, i;
for( i=0; i<l; i++) {
elements[i].style.cssText =
elements[i].style.cssText.replace(/(^|;)\s*font-[^;]+/g,"");
}
A no-library solution:
var pattern = /^\s*font-/;
var styled = document.querySelectorAll('[style]');
[].forEach.call(styled, function(element) {
var css = element.getAttribute('style');
css = css.split(';').filter(function(rule) {
return !pattern.test(rule);
}).join(';');
element.setAttribute('style', css);
});
Basically, loop through each tag with style
attribute, split into individual rules to minimize bleed (still some possible: background: url('boo;font-weight.png');
gets mangled; but it's really hard to implement a proper parser in a couple of lines, and the danger here is negligible), then only select the rules that do not start with font-
, and rebuild the style
attribute.
EDIT: Niet beat me by 1 minute, and with tighter code. +1.
we cant parse html with regex, however I ll give it a try.
search : style=(.*)font-[^;]+;
replace with: style=\1
demo here: http://regex101./r/gB6nF7/3
The regex may help you in this scenario but wont go too far.
In other cases you may use what hjpotter suggested :
replace font-[^;]+;
with ''
I would suggest to use HtmlAgilityPack instead of regex.It is just awesome!
Regex is not a good practise as html parser.