How can I create a SEO friendly dash-delimited url from a string?

Shawn picture Shawn · Jan 21, 2009 · Viewed 9.8k times · Source

Take a string such as:

In C#: How do I add "Quotes" around string in a comma delimited list of strings?

and convert it to:

in-c-how-do-i-add-quotes-around-string-in-a-comma-delimited-list-of-strings

Requirements:

  • Separate each word by a dash and remove all punctuation (taking into account not all words are separated by spaces.)
  • Function takes in a max length, and gets all tokens below that max length. Example: ToSeoFriendly("hello world hello world", 14) returns "hello-world"
  • All words are converted to lower case.

On a separate note, should there be a minimum length?

Answer

Shawn picture Shawn · Jan 21, 2009

Here is my solution in C#

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();
}