2

I browsed around for a solution and I am sure it's a simple question but still not sure how to do that. So, I have a string that contains many words and some times it has links in it. For example:

I like the website http://somesitehere.com/somepage.html and I suggest you try it too.

I want to display the string in my view and have all links automatically converted to URLs.

@Model.MyText

Even StackOverflow gets it.

3 Answers 3

1

@Hunter is right. In addition i found complete implementation in C#: http://weblogs.asp.net/farazshahkhan/archive/2008/08/09/regex-to-find-url-within-text-and-make-them-as-link.aspx.

In case original link goes down

VB.Net implementation

Protected Function MakeLink(ByVal txt As String) As String
    Dim regx As New Regex("http://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase)

    Dim mactches As MatchCollection = regx.Matches(txt)

    For Each match As Match In mactches
        txt = txt.Replace(match.Value, "<a href='" & match.Value & "'>" & match.Value & "</a>")
    Next

    Return txt
End Function

C#.Net implementation

protected string MakeLink(string txt) 
{ 
   Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase); 

   MatchCollection mactches = regx.Matches(txt); 

   foreach (Match match in mactches) { 
    txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>"); 
   }
   return txt; 
}
Sign up to request clarification or add additional context in comments.

Comments

1

One way to do that would be to do a Regular Expression match on a chunk of text and replace that url string with an anchor tag.

Comments

1

Another regex that can be used with KvanTTT answer, and has the added benefit of accepting https urls

https?://([\w+?.\w+])+([a-zA-Z0-9\~!\@#\$\%\^\&*()_-\=+\/\?.:\;\'\,]*)?

.net string representation:

"https?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.