ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToUrlString

takes a string, replacing special characters and spaces with - (one dash per one or many contiguous special charachters or spaces). makes lower-case and trims. good for seo.

Source

public static string ToUrlString(this string str) {
   if (String.IsNullOrEmpty(str)) return "";
   // Unicode Character Handling: http://blogs.msdn.com/b/michkap/archive/2007/05/14/2629747.aspx
   string stFormD = str.Trim().ToLowerInvariant().Normalize(NormalizationForm.FormD);
   var sb = new StringBuilder();
   foreach (char t in
      from t in stFormD
      let uc = CharUnicodeInfo.GetUnicodeCategory(t)
      where uc != UnicodeCategory.NonSpacingMark
      select t) {
      sb.Append(t);
   }
   return Regex.Replace(sb.ToString().Normalize(NormalizationForm.FormC), "[\\W\\s]{1,}", "-").Trim('-');
}

Example

MyWebItem.Name.ToUrlString()

Author: esp

Submitted on: 17 apr. 2011

Language: C#

Type: System.String

Views: 6206