ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Linkify

Takes a string of text and replaces text matching a link pattern to a hyperlink

Source

public static class LinkExtension {
    private readonly static Regex domainRegex = new Regex( @"(((?<scheme>http(s)?):\/\/)?([\w-]+?\.\w+)+([a-zA-Z0-9\~\!\@\#\$\%\^\&amp;\*\(\)_\-\=\+\\\/\?\.\:\;\,]*)?)", RegexOptions.Compiled | RegexOptions.Multiline );

    public static string Linkify( this string text, string target = "_self") {
        return domainRegex.Replace(
            text,
            match => {
                var link = match.ToString();
                var scheme = match.Groups["scheme"].Value == "https" ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
                
                var url = new UriBuilder( link ) { Scheme = scheme }.Uri.ToString();
                                
                return string.Format( @"<a href=""{0}"" target=""{1}"">{2}</a>", url, target, link );
            }
        );
    }
}

Example

void Main() {   
    Console.WriteLine( "This goes to the https://www.test.com website".Linkify() );
    Console.WriteLine( "This goes to the http://www.test.com website".Linkify("_blank") );
    Console.WriteLine( "This goes to the www.test.com website".Linkify() );
    Console.WriteLine( "This goes to the test.com website".Linkify("_blank") );
    Console.WriteLine( "This goes to the test.com/page.html page".Linkify() );
    Console.WriteLine( "This goes to the https://wwwtest.com/folder/page.html page".Linkify("_blank") );
}

Author: Andy T

Submitted on: 6 mei 2011

Language: C#

Type: System.String

Views: 9026