I am still not able to use regular expressions by heart, thus could not find a final solution to strip out all styles from <p style=””>…</p> using RegEx with Javascript, but leave color and background-color if they exist.
What I found:
1. Remove complete style=”…” element with RegEx:
htmlString = (htmlString).replace(/(<[^>]+) style=".*?"/i, '');
2. Remove certain styles with RegEx:
htmlString = (htmlString).replace(/font-family\:[^;]+;?|font-size\:[^;]+;?|line-height\:[^;]+;?/g, '');
Challenge: In case, we remove all styles assigned (no color exists), and style is empty (we have style=”” or style=” “), the style attribute should be removed as well.
I guess we need two lines of code?
Any help appreciated!
Example 1 (whitelisted “color” survives):
<p style="font-family:Garamond;font-size:8px;line-height:14px;color:#FF0000;">example</p>
should become:
<p style="color:#FF0000;">example</p>
Example 2 (all styles die):
<p style="font-family:Garamond;font-size:8px;line-height:14px;">example</p>
should become:
<p>example</p>
First, the proof of concept. Check out the Rubular demo.
The regex goes like this:
Broken down, it means:
Now, the replacement,
should always construct what you expect to have left!
The trick here, in case it’s not clear, is to put the “negative” case first, so that only if the negative case fails, the captures (such as the style attribute itself) would be populated, by, of course, the alternate case. Otherwise, the captures default to nothing, so not even the style attribute will show up.
To do this in JavaScript, do this:
Note that I’m doing this for fun, not because this is how this problem should be solved. Also, I’m aware that the semicolon-capture is hacky, but it’s one way of doing it. And one can infer how to extend the whitelist of styles, looking at the breakdown above.