0

Is there any existing library or code for ASP.NET MVC that can transform some string into a pretty url much like stackoverflow does with questions ?

Having the string:

Hello there! This is some weird with accénted words and funcky - / Characters (29)

to something like:

Hello-there-This-is-some-weird-accented-words-and-funcky-Characters-29

Bart Calixto
  • 19,210
  • 11
  • 78
  • 114
  • I guess there are a lot of things to take into cosideration for a simple replace. like é to e, and not having lots of --- because of string transformation and some etc I do not imagine beforehand. Take a look at the string generated from the title of this question. – Bart Calixto Oct 01 '14 at 00:09

1 Answers1

1

Well, removing diacritics has been answered before.

public static string RemoveDiacritics(string text) 
{
    var normalizedString = text.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder();

    foreach (var c in normalizedString)
    {
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}

If you take RemoveDiacritics, then all you need to do is some Regex replace, replacing all non-alpha numeric characters with a single dash.

public static string PrettyUrl(string s)
{
    return Regex.Replace(RemoveDiacritics(s), "[^a-zA-Z0-9]+", "-").Trim('-');
}

Fiddle

Community
  • 1
  • 1
Mrchief
  • 75,126
  • 20
  • 142
  • 189