Reputation:
I need to remove all chars that cant be part of urls, like spaces ,<,> and etc.
I am getting the data from database.
For Example if the the retrieved data is: Product #number 123!
the new string should be: Product-number-123
Should I use regex? is there a regex pattern for that? Thanks
Upvotes: 2
Views: 492
Reputation: 171784
An easy regex to do this is:
string cleaned = Regex.Replace(url, @"[^a-zA-Z0-9]+","-");
Upvotes: 1
Reputation: 11442
To just perform the replacement of special characters like "<" you can use Server.UrlEncode(string s)
. And you can do the opposite with Server.UrlDecode(string s)
.
Upvotes: 1
Reputation: 41929
Here is a an example on how to generate an url-friendly string from a "normal" string:
public static string GenerateSlug(string phrase)
{
string str = phrase.ToLower();
str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // invalid chars
str = Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space
str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); // cut and trim it
str = Regex.Replace(str, @"\s", "-"); // hyphens
return str;
}
You may want to remove the trim-part if you are sure that you always want the full string.
Upvotes: 2