Created
March 13, 2012 15:57
-
-
Save ProximaMonkey/2029556 to your computer and use it in GitHub Desktop.
Generate a url slug
This file contains hidden or 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
private string ToSeoFriendly(string title, int maxLength) { | |
var match = Regex.Match(title.ToLower(), "[\\w]+"); | |
StringBuilder result = new StringBuilder(""); | |
bool maxLengthHit = false; | |
while (match.Success && !maxLengthHit) { | |
if (result.Length + match.Value.Length <= maxLength) { | |
result.Append(match.Value + "-"); | |
} else { | |
maxLengthHit = true; | |
// Handle a situation where there is only one word and it is greater than the max length. | |
if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength)); | |
} | |
match = match.NextMatch(); | |
} | |
// Remove trailing '-' | |
if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1); | |
return result.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment