C# Example For Removing White Space From HTML


Example of csharp utility function to remove white spaces from HTML string. This is done with help of Regex class of dotnet framework.

private static readonly Regex RegexBetweenTags = new Regex(@">s+", RegexOptions.Compiled);
private static readonly Regex RegexLineBreaks = new Regex(@"ns+", RegexOptions.Compiled);

public static string RemoveHtmlWhitespace(string html)
{
    if (string.IsNullOrEmpty(html))
    {
        return string.Empty;
    }

    html = RegexBetweenTags.Replace(html, "> ");
    html = RegexLineBreaks.Replace(html, string.Empty);

    return html.Trim();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.