Home Blog .NET Creating a URL friendly text from string
Creating a URL friendly text from string
Written by Dicky   
Tuesday, 12 July 2011 12:56
AddThis Social Bookmark Button

I was looking at the best way to create an URL friendly text from a string. It can be used for article name or file name. After looking into several articles, most of them are using Regular Expression to replace the non-supported character.

That's until I find this very simple and elegant solution. I post the code here so we all can share the benefit:

/// <summary>
/// Creates a "slug" from text that can be used as part of a valid URL.
/// Invalid characters are converted to hyphens. Punctuation that is perfect valid in
/// a URL is also converted to hyphens to keep the result mostly text. Steps are taken
/// to prevent leading, trailing, and consecutive hyphens.
/// </summary>
/// <param name="s">String to convert to a slug</param>
/// <returns></returns>
public static string TextToSlug(string s)
    StringBuilder sb = new StringBuilder();
    bool wasHyphen = true;

    foreach (char c in s)
        if (char.IsLetterOrDigit(c))
            wasHyphen = false;
        else if (c != '\'' && !wasHyphen)
            wasHyphen = true;

    // Avoid trailing hyphens
    if (wasHyphen && sb.Length > 0)

    return sb.ToString();

Hope this is useful.