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

后端 未结 12 1541
再見小時候
再見小時候 2020-12-05 19:16

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:

12条回答
  •  醉话见心
    2020-12-05 19:57

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

提交回复
热议问题