Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to convert a URL to a hyperlink in a C# string?

I am consuming the Twitter API and want to convert all URLs to hyperlinks.

What is the most effective way you've come up with to do this?

from

string myString = "This is my tweet check it out http://tinyurl.com/blah";

to

This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>
like image 622
Nathan Birkes Avatar asked Aug 28 '08 15:08

Nathan Birkes


People also ask

How do I turn a URL into a hyperlink?

Create a hyperlink to a location on the webSelect the text or picture that you want to display as a hyperlink. Press Ctrl+K. You can also right-click the text or picture and click Link on the shortcut menu. In the Insert Hyperlink box, type or paste your link in the Address box.

How do I copy and paste a clickable link?

Here's how to do it in 3 easy steps: Right-click the URL you want to copy. Select 'copy' from the popup menu. Navigate to wherever you wish to share the link, right-click then paste.


1 Answers

Regular expressions are probably your friend for this kind of task:

Regex r = new Regex(@"(https?://[^\s]+)");
myString = r.Replace(myString, "<a href=\"$1\">$1</a>");

The regular expression for matching URLs might need a bit of work.

like image 84
samjudson Avatar answered Sep 27 '22 19:09

samjudson