Remove Html Tags from a String, C#.NET, ASP.NET


Task: Remove HTML tags from a string.

Description: When we update content using WYSIWYG HTML editor (ck-editor) then it used HTML tag for formatting the content. But some time we need the same content without any formatting so then we require the removing HTML tag from that content.

Here I use two variation for this first one is using a simple loop And Second one is using Regex.

// How convert a html tag to blank space in a string using c#.net/asp.net code
// Replacing the html tag <> to blank space, you can copy data with html tag and then convert to normal text
// eg. INPUT   -->  <div width="5">Hemant Singh <i>Rautela</i></div>
        OUTPUT--> Hemant Singh Rautela

//
//C#.NET , ASP.NET
// Method 1 : (Using Character Array)

 public string replace(string s)
 {
    int l = s.Length;
    int j = 0;
    char[] ch = s.ToCharArray();
    s = "";
    for (int i = 0; i < l; i++)
    {
        if (ch[i] == '<')
            j = 1;
        if (j == 1)
        {
            if (ch[i] == '>')
                j = 0;
            ch[i] = ' ';
        }
        s = s + ch[i].ToString();
    }
    return (s);
 }


// Method 2 (Using Regular Expressions- Regex)

 using System.Text.RegularExpressions;
 public string replace(string s)
 {
   String result = Regex.Replace(s, @"<[^>]*>", String.Empty);
 }

1 comment: