title: How to get links to URLs in text in ASP.NET MVC 4 with Razor syntax?
body: <p>I have a model with a text field. The text <strong>can</strong> contain several URLs. It does not have to contain URLs and it does not have a specific format.</p>
  
  <p>Using </p>
  
  <pre><code>@Html.DisplayFor(model =&gt; model.TextWithSomeUrls)
  </code></pre>
  
  <p>the text and the URLs are displayed like normal text of course. I would like to get the URLs displayed as working individual links though. Is there a helper method for this in ASP.NET / Razor?</p>
  
  <p><strong>Edit</strong>: Right now the output is:</p>
  
  <pre><code>http://www.google.com, foo: bar;  http://www.yahoo.com
  </code></pre>
  
  <p>Which is exactly the content of the text field.</p>
  
  <p>But I want to get the URLs and only the URLs rendered as links like this:</p>
  
  <pre><code>&lt;a href="http://www.google.com"&gt;http://www.google.com&lt;/a&gt;, foo: bar; &lt;a href="http://www.yahoo.com"&gt;http://www.yahoo.com&lt;/a&gt;
  </code></pre>
  
  <p><strong>My solution</strong>:</p>
  
  <pre><code>public static partial class HtmlExtensions
  {
      private const string urlRegEx = @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;amp;:/~\+#]*[\w\-\@?^=%&amp;amp;/~\+#])?)";
  
      public static MvcHtmlString DisplayWithLinksFor&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression)
      {
          string content = GetContent&lt;TModel, TProperty&gt;(htmlHelper, expression);
          string result = ReplaceUrlsWithLinks(content);
          return MvcHtmlString.Create(result);
      }
  
      private static string ReplaceUrlsWithLinks(string input)
      {
          Regex rx = new Regex(urlRegEx);
          string result = rx.Replace(input, delegate(Match match)
          {
              string url = match.ToString();
              return String.Format("&lt;a href=\"{0}\"&gt;{0}&lt;/a&gt;", url);
          });
          return result;
      }
  
      private static string GetContent&lt;TModel, TProperty&gt;(HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression)
      {
          Func&lt;TModel, TProperty&gt; func = expression.Compile();
          return func(htmlHelper.ViewData.Model).ToString();
      }
  }
  </code></pre>
  
  <p>This extension can now be used in views:</p>
  
  <pre><code>@Html.DisplayWithLinksFor(model =&gt; model.FooBar)
  </code></pre>