Created
January 4, 2018 07:57
-
-
Save RickStrahl/c3a1a3bd18423b67e2734d761fb62593 to your computer and use it in GitHub Desktop.
Generate Slug
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
/// <summary> | |
/// Creates a unqique slug | |
/// </summary> | |
/// <param name="titleText"></param> | |
/// <returns></returns> | |
public string CreateSlug(string titleText = null) | |
{ | |
if (titleText == null) | |
titleText = Title; | |
if (string.IsNullOrEmpty(titleText)) | |
{ | |
Slug = null; | |
return null; | |
} | |
StringBuilder sb = new StringBuilder(); | |
bool isInvalidBreakChar = true; | |
foreach (char ch in titleText.Trim(' ','*','-','.','!','?')) | |
{ | |
if (ch == ' ' || ch == '.' || ch == ',') | |
{ | |
if (!isInvalidBreakChar) | |
sb.Append("-"); | |
isInvalidBreakChar = true; | |
} | |
else if (ch == '-') | |
{ | |
if (!isInvalidBreakChar) | |
sb.Append("--"); | |
isInvalidBreakChar = true; | |
} | |
else if (char.IsLetterOrDigit(ch)) | |
{ | |
sb.Append(ch); | |
isInvalidBreakChar = false; | |
} | |
} | |
string slug = sb.ToString(); | |
slug = slug.TrimEnd('-'); | |
if (Project != null) | |
{ | |
int postFix = 1; | |
string origSlug = slug; | |
while (Project.Topics.Any(t => t.Slug == slug)) | |
{ | |
slug = origSlug + "-" + postFix; | |
postFix++; | |
} | |
} | |
Slug = slug; | |
return Slug; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment