Most content management systems automatically convert your post title into a slug which forms the part of a URL used to locate the post. Here’s how to do it in C#
The term slug comes from the world of newspaper production and is the name used to reference the story. A content management system uses the slug portion of the URL to load the post (WordPress call it a Permalink).
For example the slug for this post is csharp-generate-slug and the full URL is: https://developingsoftware.com/csharp-generate-slug.
It’s a good idea to make a slug all lower case, replace dashes with spaces, and only use letters and digits.
Let’s see some sample code that generates a slug from a post title in C#
Example Code
public static class SlugUtil
{
public static string Slugify(string input)
{
if (string.IsNullOrEmpty(input))
{
throw new ArgumentNullException("input");
}
var stringBuilder = new StringBuilder();
foreach(char c in input.ToArray())
{
if (Char.IsLetterOrDigit(c))
{
stringBuilder.Append(c);
}
else if (c == ' ')
{
stringBuilder.Append("-");
}
}
return stringBuilder.ToString().ToLower();
}
}
The code above is really simple and does a basic job of replacing any spaces with dashes, making the slug lowercase and stripping out any characters that are not a letter or digit.
Example Usage
string title = "How to Convert a Post Title into a Friendly URL in C#";
string slug = SlugUtil.Slugify(title);
Now after running the post title through the Slugify
function you will get a user friendly slug that can be used to make up the full URL to your post. In the example above the full URL would be:
https://developingsoftware.com/how-to-convert-a-post-title-into-a-friendly-url-in-c
If you find the slug is too long, you could always make it editable by the user and use the generated slug when first creating the post.