开发者

Convert input string to a clean, readable and browser acceptable route data

开发者 https://www.devze.com 2023-03-11 07:18 出处:网络
Scenario: There is a title called \"AJAX, JSON & HTML5! The future of web?\" Would like to convert this into this \"ajax-json-html5-the-future-of-web\"

Scenario:

There is a title called "AJAX, JSON & HTML5! The future of web?"

Would like to convert this into this "ajax-json-html5-the-future-of-web"

Basically what I need is a function that strips out all the non alphabets and then replace them with a single hyphen and lowercase that.

Problem:

With some effort I could do that with String.Replace or String.CharAt but I think thats all too messy. Am I correct? I believe Re开发者_如何学运维gex is the way to go. As my Regex is very rusty I am unable to get something that shows the desired output.:)

Disclaimer: This is basically a Give me the Codez. But I have pretty much covered my options I guess.


An example using Regex - this should get you in the right direction (Edit - added clearing off the trailing dash so it looks nicer)

    var input = "This is some amazing Rexex Stuff!";
            input = Regex.Replace(input, @"[\W]+", "-").ToLower();
            input = Regex.Replace(input, @"[-]+$", "");
            Console.Write(input);
            Console.Read();


Here is some code I used to this a while back, it's not perfect but it should get you started:

EDIT: Still ugly but output is better: ajax-json-html5-the-future-of-web-

string title = "AJAX, JSON & HTML5! The future of web?";

title = Regex.Replace(title, @"&|&", "-");

StringBuilder builder = new StringBuilder();

for (int i = 0; i < title.Length; i++)
{
    if (char.IsLetter(title[i]) || char.IsDigit(title[i]))
        builder.Append(title[i]);
    else
        builder.Append('-');
}
string result = builder.ToString().ToLower();
result = Regex.Replace(result, "-+", "-");
0

精彩评论

暂无评论...
验证码 换一张
取 消