2sic / razor-blade

A pretty awesome library to make work in Razor easier and more productive
MIT License
6 stars 2 forks source link

SeoFragment, ToSlug, etc #20

Open jeremy-farrance opened 2 years ago

jeremy-farrance commented 2 years ago

I read in your read-me about the WIP for SeoFragment().

We've used this for years to convert what users type into Title (and other fields) to properly convert to URL slugs for SEO. Even if you don't use the code as is or want to use RegEx, it might be good as a check list or comparison for your own code.

Only issue I remember is that it doesn't (and probably should) remove trailing dashes .ToSlug("this that-") should resolve to this-that but the routine below leaves the trailing dash.

    // Turn any text or title in to a URL Slug
    // source/original: https://stackoverflow.com/questions/2920744/url-slugify-algorithm-in-c
    public string ToSlug(string phrase)
    {
        byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(phrase);
        string str = System.Text.Encoding.ASCII.GetString(bytes);
        str = str.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;
    }