Skip to content

SeoFragment, ToSlug, etc #20

Description

@jeremy-farrance

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;
	}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions