Make a Hashtag in a string clickable using Regex

by Edward 15 November 2011 19:09

I recently wanted to get hashtags from a string and convert this to a clickable link (think Twitter integration). There are several ways of doing this, but I wanted to use regex. I find using regex easier to use when manipulating string values, then say using a for loop to check for the hash for each word in a string. If you want to use the loop method, you will need to split the string and then loop through each word and then check for a hashtag at the beginning of the word, and then make it clickable using an ahref tag. You would possibly also have to encode '#' with '%23' to parse the string and display on the webpage.

Below is a small function that will take the input and replace a hashtag with a clickable link.

Code Sample:


public static string GetHashTag(string urlText)
            Regex urlregex = new Regex(@"(#)((?:[A-Za-z0-9-_]*))", RegexOptions.IgnoreCase 
               | RegexOptions.Compiled);
            return urlregex.Replace(urlText, "<a href=\"$1$2\" style=\"color: #f68b1f;\">$1$2</a>");

Tags: , , ,

ASP.NET | Other

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List