Dalvir Saini
Dalvir Saini

Reputation: 390

How to create smart urls containing special characters?

I have to create urls for my academy courses, and these courses are containing special characters like +, #, ?, _, -, etc.

How I can replace this with some smart characters? And is there any way to do it without encoding?

Upvotes: 0

Views: 73

Answers (1)

trashr0x
trashr0x

Reputation: 6565

I'm assuming you're asking about URL slugs, in which case have a look at this answer.

Code included below.

/// <summary>
/// Produces optional, URL-friendly version of a title, "like-this-one". 
/// hand-tuned for speed, reflects performance refactoring contributed
/// by John Gietzen (user otac0n) 
/// </summary>
public static string URLFriendly(string title)
{
    if (title == null) return "";

    const int maxlen = 80;
    int len = title.Length;
    bool prevdash = false;
    var sb = new StringBuilder(len);
    char c;

    for (int i = 0; i < len; i++)
    {
        c = title[i];
        if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
        {
            sb.Append(c);
            prevdash = false;
        }
        else if (c >= 'A' && c <= 'Z')
        {
            // tricky way to convert to lowercase
            sb.Append((char)(c | 32));
            prevdash = false;
        }
        else if (c == ' ' || c == ',' || c == '.' || c == '/' || 
        c == '\\' || c == '-' || c == '_' || c == '=')
        {
            if (!prevdash && sb.Length > 0)
            {
                sb.Append('-');
                prevdash = true;
            }
        }
        else if ((int)c >= 128)
        {
            int prevlen = sb.Length;
            sb.Append(RemapInternationalCharToAscii(c));
            if (prevlen != sb.Length) prevdash = false;
        }
        if (i == maxlen) break;
    }

    if (prevdash)
        return sb.ToString().Substring(0, sb.Length - 1);
    else
        return sb.ToString();
}

You can find RemapInternationalCharToAscii here.

You would then do something along these lines:

string courseName = "Biology #101 - A Beginner's Guide!";

string urlFriendlyCourseName = URLFriendly(courseName);
//outputs biology-101-a-beginners-guide

Update

Per your question in the comments, you could include your CourseID in the URL and use that to match a DB entry (i.e. match on 12345 in http://mycourses.com/12345/biology-101-a-beginners-guide/). You should also store the result of URLFriendly(courseName) in a DB column (e.g. CourseSlug) so that you can match on CourseID, CourseSlug, or both.

Upvotes: 1

Related Questions