-1

In my website, I want to give a feature "to recognize the link". You can see the example in Facebook. Whenever we share a link, it automatically detects it and also find thumbnails. Also If we do the same in Status update, It does the same.

I want to implement the same functionality using asp.net with c#.

Any tutorials, links or demos will be helpful. If you can, please share the logic too.

2
  • 3
    You should try some codings first, before you ask. Basically it is a onchange or onkeyup event matching contents with regex. Commented Jan 8, 2013 at 7:21
  • @ShivanRaptor: Thanks.Exactly, I want the regex for it. Commented Jan 8, 2013 at 7:23

1 Answer 1

3

This is what i use. On description I use 40 characters, if you want the complete link in description too just remove the substring part...

static string LinksToHTML(string str)
    {
         Regex urlRx = new Regex(@"(?<url>((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+))", RegexOptions.IgnoreCase);

        MatchCollection matches = urlRx.Matches(str);

        foreach (Match match in matches)
        {
            var url = match.Groups["url"].Value;
            str = str.Replace(url, string.Format("<a href=\"{0}\" target=\"blank\">{1}</a>", url, (url.Length > 40 ? url.Substring(0, 40) + "..." : url)));

            //str = str.Replace(url, string.Format("<a href=\"{0}\" target=\"blank\">{1}</a>", url, url));
        }

        return str;
    }
Sign up to request clarification or add additional context in comments.

5 Comments

you should handle the link that starts with https
Thanks Shivan, you're right, I modified it.
I think I liked this one better: stackoverflow.com/questions/6173/…
Modified mine again according to stackoverflow.com/questions/6173/…
Yes I agree with this answer, regular expressions are designed for this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.