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.
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, "-+", "-");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With