hotcoder
hotcoder

Reputation: 3256

Remove width and height of img tag in given string in asp.net

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?

Upvotes: 3

Views: 3560

Answers (4)

dsf
dsf

Reputation: 1

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);

Upvotes: -2

Oleks
Oleks

Reputation: 32333

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.

Upvotes: 1

ridgerunner
ridgerunner

Reputation: 34395

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)

Upvotes: 2

JohnFx
JohnFx

Reputation: 34909

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.

Upvotes: 1

Related Questions