Reputation: 114
I am trying to remove all "color" style from element style using regex but I am failing miserably.
Example of a style
cursor: pointer;background-color: yellow;color: lightgray;
Example of what the style should become
cursor: pointer;background-color: yellow;
This is the regex I am using color:[^;]+;
It captures background-color and removes the part after background.
Upvotes: 2
Views: 142
Reputation: 114
A little update on the solution.
dystroy, solution just has one small issue dealing with backgroud-image with base64 input. Just wanted to add regular expression for splitting the style
arr = s.match(/background-image\s*:\s*url\s*\(\s*data:image[^)]+\)?|[a-zA-Z-]+:[^;]+/gi);
That should give you an array containing all the elements. So far it works.
Upvotes: 0
Reputation: 382464
This regex works for me :
[\s;]color:[^;]+(?=;)|^color:[^;]+;
You'll see it handles differently the case where the color is the first parameter.
var style = "cursor: pointer;background-color: yellow;color: lightgray;";
var replaced = style.replace(/[\s;]color:[^;]+(?=;)|^color:[^;]+;/g, '')
Note that, even if using a regex isn't that bad here, this operation could be done with greater confidence with a simple splitting+filtering :
var replaced = style.split(';').filter(function(v){
return v.split(':')[0].trim()!='color'
}).join(';');
Upvotes: 2