timestee
timestee

Reputation: 1096

How to remove some css properties without the paticular one using regular expression?

Example : Just keep the color properties.

Given:

<span style="margin-left: 2em;color: #008000;font-size:14px;">some text</span>

Output:

<span style="color: #008000;">some text</span>

Upvotes: 0

Views: 248

Answers (3)

Byzod
Byzod

Reputation: 486

If you do want to use regex to do this work, here's some code snippet; But I still recommend you handle this with style object.

Search style=\"[^\"]*?([cC]olor:\s#[0-9a-fA-F]{1,6};?)[^\"]*?\"

Replace with style="$1"

Upvotes: 0

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10795

Here is a sketch of solution using Xml.Linq:

XElement Load(string xml)
{
    using (var reader = new StringReader(xml))
        return XElement.Load(reader);
}

string ProcessStyles(string input)
{
    var root = Load(input);
    var allElements = root.Descendants();
    var styleAttributes = allElements.Select(e => e.Attribute(XName.Get("style"))).Where(a => a != null);
    foreach (var styleAttribute in styleAttributes)
    {
        var value = styleAttribute.Value;
        var newValue = ProcessCss(value);
        styleAttribute.SetValue(newValue);
    }

    return root.ToString();
}

string ProcessCss(string value)
{
    var cssTokens = value.Split(';').Select(t => t.Trim());

    // implement your filtering rules here
    var filtered = cssTokens.Where(t => t.StartsWith("color"));

    return String.Join(";", filtered);
}

The solution assumes certain structure of "style" attribute. It will not work with more complex CSS (e.g. with comments).

Also note that the input string has to be a well-formed XML document. (HTML5 generally does not have to be a well-formed XML).

Upvotes: 1

David Thomas
David Thomas

Reputation: 253476

This answer was written on the assumption that JavaScript was being used. While this answer is still useful (under that assumption) the language has since been specified as C#. So this answer has become incorrect.


Given the HTML:

<span style="margin-left: 2em;color: #008000;font-size:14px;">some text</span>

The following JavaScript should work (currently untested):

var spans = document.getElementsByTagName('span'),
    color;

for (var i=0,len=spans.length;i<len;i++){
    color = spans[i].style.color;
    spans[i].removeAttribute('style');
    spans[i].style.color = color;
}​

JS Fiddle demo.

Upvotes: 1

Related Questions