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

toSlug

Generate slugs for friendly urls.

Source

public static String toSlug(this string text)
{
   String value = text.Normalize(NormalizationForm.FormD).Trim();
    StringBuilder builder = new StringBuilder();

    foreach (char c in text.ToCharArray())
        if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
            builder.Append(c);

    value = builder.ToString();

    byte[] bytes = Encoding.GetEncoding("Cyrillic").GetBytes(text);

    value = Regex.Replace(Regex.Replace(Encoding.ASCII.GetString(bytes), @"\s{2,}|[^\w]", " ", RegexOptions.ECMAScript).Trim(), @"\s+", "_");

    return value.ToLowerInvariant();
}

Example

Console.WriteLine(@"I'm a cute Post Title/""\/".toSlug());
// => i_m_a_cute_post_title

Author: Lucas

Submitted on: 30 nov 2009

Language: C#

Type: System.String

Views: 5282