Convert Url String to Hyperlinks

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text;
public partial class ReplaceString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strUrl = MakeUrl("Hello. This is my site http://www.google.com Please Visit.");
Response.Write(strUrl);
}
private static string MakeUrl(string input)
{
var work = input.Split(' ');
var output = new StringBuilder(2 * input.Length);
for (int i = 0; i <>
{
var element = work[i];
if (element.StartsWith("http://"))
{
var site = element.Replace("http://", "");
}
else if (element.StartsWith("www"))
{
var site = element.Replace("http://", "");
}
else if (element.EndsWith(".com"))
{
var site = element.Replace("http://", "");
}
output.Append(element + " ");
}
return output.ToString();
}

}

 And the Final output will be like this....

 Hello. This is my site http://www.google.com Please Visit.

 

3 Comments

  • var _protocolPattern = new Regex(@"(?&lt;![\]""\&gt;=])(((news|(ht|f)tp(s?))\://)[\w\-\*]+(\.[\w\-/~\*]+)*/?)([\w\?=&amp;/;\+%\*\:~,\.\-\$\|@#])*", RegexOptions.Compiled | RegexOptions.IgnoreCase);

    text = _protocolPattern.Replace(text, match =&gt; String.Format("&lt;a href=\"{0}\"&gt;{0}&lt;/a&gt;", match.Value));

    Don't you think that's easier?

  • Hi Jeff,
    The Regex that u suggested would work only if the string starts with http whereas the above method can be used to check for the endswith also...

  • No, it'll work with any of the protocols. And that wasn't really the point anyway... why wouldn't you use RegEx? Two lines beats what you're suggesting.

Comments have been disabled for this content.