Your partner in IT success

A specialized company in providing high quality consultancy on analysis, architecture and development projects

 
23
Jan
.NET / ASP.NET / C# / MVC / Web

How to generate a friendly URL? (revisited)

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();
        }
    }
}
You’ll notice that the replacement argument is now of type Char, as this is more logic to replace a character with a single other character.
Posted by Fabian Vilers, Consulting Principal

Add your comment