Remove script and link tags from string

Viewed 273

I am trying to remove script and link tags from a string. Below is what I got till now.

Code

rawHtml = rawHtml.Remove(rawHtml.IndexOf("<script"), (rawHtml.LastIndexOf("</script>") - 
          rawHtml.IndexOf("<script")) + 5);

rawHtml = rawHtml.Remove(rawHtml.IndexOf("<link"), (rawHtml.LastIndexOf("/>") - 
          rawHtml.IndexOf("<link")) + 3);

Is there better way without manually writing the numbers ?

2 Answers

This will remove all contents between script, link and style tags, then remove the html tags (but keep the content) from the rest.

NOTE: Following @yelliver improvement on my previous answer, have incorporated that (having upvoted) and addressed your point about links.

/// <summary>
/// Helper method to strip html tags from html
/// </summary>
/// <param name="htmlText">raw html</param>
/// <returns>string without html tags</returns>
public string StripHTML(string hTMLText)
{
    // Remove script and style tags
    Regex rRemScript = new Regex(@"<(script|style)[^>]*>[\s\S]*?</\1>");
    hTMLText = rRemScript.Replace(hTMLText, "");

    // Remove link tags AND CONTENTS
    Regex rRemLink = new Regex(@"<link[\s\S]*?/>");
    hTMLText = rRemLink.Replace(hTMLText, "");

    // Strip other html tags (leaving contents)
    Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
    return reg.Replace(hTMLText, "");
}

Using backreferences, I improve @HockeyJ answer: Instead of:

Regex rRemScript = new Regex(@"<script[^>]*>[\s\S]*?</script>");
hTMLText = rRemScript.Replace(hTMLText, "");

// Remove link content
Regex rRemLink = new Regex(@"<link[^>]*>[\s\S]*?</link>");
hTMLText = rRemLink.Replace(hTMLText, "");

// Remove style content
Regex rRemStyle = new Regex(@"<style[^>]*>[\s\S]*?</style>");
hTMLText = rRemStyle.Replace(hTMLText, "");

Just use:

Regex rRemScript = new Regex(@"<(script|link|style)[^>]*>[\s\S]*?</\1>");
hTMLText = rRemScript.Replace(hTMLText, "");
Related