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.

 

Published Friday, May 06, 2011 12:59 PM by Stanly
Filed under: ,

Comments

# re: Convert Url String to Hyperlinks

Friday, May 06, 2011 6:07 PM by Jeff

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

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

Don't you think that's easier?

# re: Convert Url String to Hyperlinks

Monday, May 09, 2011 4:53 AM by Stanly

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...

# re: Convert Url String to Hyperlinks

Monday, May 09, 2011 12:41 PM by Jeff

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.

Leave a Comment

(required) 
(required) 
(optional)
(required)