23
Jan
Jan
Some days ago, I blogged about on how to generate a friendly URL. The pasted code was good, but far from being perfect. There was some case where the generated URL was pretty ugly.
Imagine that we try to transform a string with an unreserved character immediately followed by a separator? For example: This -is- a test with generate This--is--a-test which is not what we could expect.
I’ve managed to update my code with a small fix. Here’s the listing.
using System;
using System.Globalization;
using System.Linq;
using System.Text;
namespace DevOne.Extensions
{
public static class StringExtensions
{
private static char[] _friendlyUrlCharacters = new char[] { '-', '.', '_', '~' };
public static string ToUrlFriendly(this string input, char replacement = '-')
{
StringBuilder sb = new StringBuilder();
char nextChar = '\0';
foreach (char c in input.Normalize(NormalizationForm.FormD).ToCharArray())
{
if (Char.IsLetter(c))
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
if (uc != UnicodeCategory.NonSpacingMark)
{
nextChar = c;
}
}
else if (Char.IsDigit(c))
{
nextChar = c;
}
else if (_friendlyUrlCharacters.Contains(c) && nextChar != replacement)
{
nextChar = c;
}
else if (Char.IsSeparator(c) && nextChar != replacement)
{
nextChar = replacement;
}
else
{
continue;
}
sb.Append(nextChar);
}
return sb.ToString();
}
}
}
0 comment
permalink


