Thursday, 1 August 2013

Automatically hyperlink URL and Email

Add namespace using System.Text.RegularExpressions; 

Html:

<asp:TextBox id="InputTextBox" style="Z-INDEX: 101; LEFT: 168px; POSITION: absolute; TOP: 96px"
runat="server" Height="64px" Width="472px"></asp:TextBox>
<asp:Label id="lbContent" style="Z-INDEX: 102; LEFT: 168px; POSITION: absolute; TOP: 208px"
runat="server" Height="99px" Width="473px" BorderStyle="Ridge" BorderColor="Transparent"></asp:Label>
<asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 176px; POSITION: absolute; TOP: 72px" runat="server"
Width="240px" Font-Bold="True" ForeColor="#ff3366">Input URL or other text here:</asp:Label>
<asp:Button id="Button1" 
            style="Z-INDEX: 104; LEFT: 376px; POSITION: absolute; TOP: 168px" runat="server"

Text="Submit" onclick="Button1_Click"></asp:Button>

Code Behind:
on Button click

 protected void Button1_Click(object sender, EventArgs e)
        {
            string strContent = InputTextBox.Text;
            Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
            strContent = urlregex.Replace(strContent, "<a href=\"$1\" target=\"_blank\">$1</a>");
            Regex emailregex = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
            strContent = emailregex.Replace(strContent, "<a href=mailto:$1>$1</a>");
            lbContent.Text += "<br>" + strContent;

        }

output:



No comments:

Post a Comment