Łukasz Gąsior
  • Home
  • now!
  • Blog
  • Po polsku
Social Links
Twitter
LinkedIn
Facebook
YouTube
Reddit
Instagram
GitHub
Medium
RSS
Łukasz Gąsior
  • Home
  • now!
  • Blog
  • Po polsku

Posts by tag

url

1 post
  • Po polsku

Quick Tip: 06. zamieniamy URL na link

  • 2009-12-04
  • 3 komentarze

Dzisiaj prosty przykład jak w tekście zamienić url na link, czyli np. użytkownik wpisuje:
“Zapraszam na moją stronę http://gasior.net.pl”
a my wyświetlając ten tekst chcemy otrzymać coś takiego
“Zapraszam na moją stronę <a href=”http://gasior.net.pl”>http://gasior.net.pl</a>”
Z pomocą przychodzą wyrażenia regularne:
[sourcecode language=”csharp”] protected string ConvertUrlsToLinks(string msg)
{
Regex r = new Regex("(http://[^ ]+)");
return r.Replace(msg, "<a href="$1">$1</a>");
}
[/sourcecode] Jeżeli zachodzi taka potrzeba możemy ten sam efekt uzyskać w JavaScripcie:
[sourcecode language=”csharp”] var objRegExp = /(http:[^ ]+)/g;
var convertedValue = msg.replace(objRegExp, "<a href=’$1′>$1</a>");
[/sourcecode] EDIT:
w nawiązaniu do słusznej uwagi z komentarza (użytkownik apl) podaję poprawioną, dokładniejszą metodę:
[sourcecode language=”csharp”] var reg = @"((www.|(http|https)+://)[&#95;.a-z0-9-]+.[a-z0-9/&#95;:@=.+?,##%&~-]*[^.|’|# |!|(|?|,| |>|<|;|)])";
Regex r = new Regex(reg, RegexOptions.IgnoreCase);
return r.Replace(msg, "<a href="$1">$1</a>").Replace("href="www", "href="http://www");
[/sourcecode]

Share
click & help!
Nakarm dziecko!
Follow me
RESHARPER ESSENTIALS
ReSharper Essentials
CODINGTV();
codingtv();
Twitter Feed
Categories
  • Azure Cloud (6)
  • Po polsku (104)
  • Windows (1)
Featured Posts
  • Azure Activity Log – Change History
    • 2020-09-29
  • Diagram Driven Cloud Infrastructure with Cloud Maker
    • 2020-09-22
  • Azure ARM template, but it is not JSON!
    • 2020-09-15
About
👍 Cloud | DevOps | Development | Technical Leadership | 📗Author of "ReSharper Essentials
© 2019 Łukasz Gąsior. All rights reserved.
hosted with ♥️ on webio | Polityka prywatności

Input your search keywords and press Enter.