@manhnguyenv

Welcome to my blog!

String (C#)

June 22, 2018 13:17

String (C#) - Slug (edit)

Input: Chúng tôi là chiến sỹ

Output: chung-toi-la-chien-sy

    //https://stackoverflow.com/questions/2920744/url-slugify-algorithm-in-c
    //https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net
//https://www.pipiscrew.com/2017/05/generating-url-slugs-in-net-core/ public static class Slug { public static string GenerateSlug(this string phrase) { string str = phrase.RemoveDiacritics().ToLower(); // invalid chars str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // convert multiple spaces into one space str = Regex.Replace(str, @"\s+", " ").Trim(); // cut and trim str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); str = Regex.Replace(str, @"\s", "-"); // hyphens return str; } public static string RemoveDiacritics(this string text) { var s = new string(text.Normalize(NormalizationForm.FormD) .Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) .ToArray()); return s.Normalize(NormalizationForm.FormC); } }

Categories