Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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 Regex 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.

like image 288
naveen Avatar asked Jun 09 '11 10:06

naveen


2 Answers

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();
like image 100
Bob Palmer Avatar answered Nov 15 '22 11:11

Bob Palmer


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, "-+", "-");
like image 34
aligray Avatar answered Nov 15 '22 11:11

aligray