Your better URLs – Slugify

We have an e-commerce shop, so that we have products there. There should be Friendly URL for every product, so last part would be the name of a product.

Product name is:

dovre Gore-Tex Pro Shell Jacket (M/W)

It can be changed to: (lets say it looks nice)

dovre-gore-tex-pro-shell-jacket-mw

The full URL would be then:

example.com/Products/1234/dovre-gore-tex-pro-shell-jacket-mw/
public static string GenerateSlug(string phrase)
{
    string str = RemoveAccent(phrase).ToLower();
    // invalid chars           
    str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
    // convert multiple spaces into one space   
    str = Regex.Replace(str, @"\s+", " ").Trim();
    // cut and trim 
    str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim();
    str = Regex.Replace(str, @"\s", "-"); // hyphens   
    return str;
}

public static string RemoveAccent(string txt)
{
    byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
    return System.Text.Encoding.ASCII.GetString(bytes);
}

The above code have been taken from answer with most votes from URL Slugify alrogithm in C#?

Alternative

You can render you URL using

HttpUtility.UrlEncode("dovre Gore-Tex Pro Shell Jacket (M/W)")

It’s not standard and will encode a lot of characters (like %2f) which is better to just omit like in Slugify(…).

example.com/Products/1234/dovre+Gore-Tex+Pro+Shell+Jacket+(M%2fW)/

A look into dictionary

Slug the part of an URL which identifies a page using human-readable keywords

Reklamy
Ten wpis został opublikowany w kategorii EpiServer, Programowanie i oznaczony tagami , , , , . Dodaj zakładkę do bezpośredniego odnośnika.

4 odpowiedzi na „Your better URLs – Slugify

  1. Pingback: dotnetomaniak.pl

  2. However you should include parts from the answer that are removing accent. Otherwise slufigy will remove characters like ł, ą, ó, ę etc.

    ł, ą etc are just an examples.

  3. @gutek Of course you’re right. I saw this code, but „Cyrillic” sounded for me like I don’t need it. But it turns out that it helps as well for all non english characters. My mistakes, next time I should test more.

  4. Updated code works as well for norwegian letters: fjørå -> fjora

Możliwość komentowania jest wyłączona.