How do I generate a Friendly URL in C#?

前端 未结 4 1681
生来不讨喜
生来不讨喜 2020-12-04 10:10

How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL\'s like Stack Overflow?

4条回答
  •  鱼传尺愫
    2020-12-04 10:54

    This gets part of the way there (using a whitelist of valid characters):

    new Regex("[^a-zA-Z-_]").Replace(s, "-")
    

    It does, however, give you a string that ends with "--". So perhaps a second regex to trim those from the beginning/end of the string, and maybe replace any internal "--" to "-".

提交回复
热议问题