Created
October 1, 2018 10:24
-
-
Save dehghani-mehdi/6717bb54304e2e188766ff31da7fa740 to your computer and use it in GitHub Desktop.
Generate clean url slug in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public string Slugify(string s) | |
{ | |
if (string.IsNullOrWhiteSpace(s)) return ""; | |
// removing extra spaces and keeping just one | |
s = string.Join(" ", Regex.Split(s, @"\s+")).ToLower(); | |
var specialPhases = new Dictionary<string, string> | |
{ | |
{"c#","c-sharp"}, | |
{"f#","f-sharp"}, | |
{"_","-"}, | |
}; | |
foreach (var item in specialPhases) s = s.Replace(item.Key, item.Value); | |
var matches = Regex.Matches(s, "[\\w]+"); | |
var words = new List<string>(); | |
foreach (Match m in matches) words.Add(m.Value); | |
return string.Join("-", words); | |
} | |
// Usage | |
var slug = Slugify("I love C# ~!@#$%^&*()_+=-|\\/';:}{[]"); // i-love-c-sharp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment