3

I have some html string that is coming from telerik radeditor, it may contain images tags with width and height. I want to remove those width and height properties. How can I do this in code using regex or something else in asp.net?

1
  • please show a sample html string and your desired o/p. Commented Apr 27, 2011 at 4:44

4 Answers 4

2

Two Regex replace statements will do the job pretty well:

str = Regex.Replace(str, @"(<img[^>]*?)\s+height\s*=\s*\S+",
        "$1", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"(<img[^>]*?)\s+width\s*=\s*\S+",
        "$1", RegexOptions.IgnoreCase);

(This is a C# snippet - not sure if ASP.NET is the same)

Sign up to request clarification or add additional context in comments.

Comments

1

There are a lot of mentions regarding not to use regex when parsing HTML, so you could use e.g. Html Agility Pack for this:

HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);

var images = document.DocumentNode.SelectNodes("//img");
foreach (HtmlNode image in images)
{
    if (image.Attributes["width"] != null)
    {
        image.Attributes["width"].Remove();
    }
    if (image.Attributes["height"] != null)
    {
        image.Attributes["height"].Remove();
    }
}

this will remove width and height attribute from images in your html.

Comments

1

Not sure I understand the question, but why not just omit them in the first place instead of trying to remove them?

In your ASPX file....

<img src="images/myimage.jpg">

And for the love of God, don't try to strip them out with Regex.

1 Comment

Why not use regex? Genuinely interested. Thanks.
-2
str = Regex.Replace(str, @"(<img[^>]*?)\s+height\s*=\s*\S+",
        "$1", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"(<img[^>]*?)\s+width\s*=\s*\S+",
        "$1", RegexOptions.IgnoreCase);

1 Comment

That is exactly the same answer as the one from ridgerunner, minus the text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.