Language: EN

csharp-slugify

How to create slugs in C# with Slugify

Slugify is an open-source .NET library that allows you to generate slugs from text strings.

Slugs are a way of representing a text string that is widely used in URLs and resource identification systems on the web.

Basically, they are a “sanitized” way of encoding text, removing characters such as spaces, accents, and other symbols, so that they are compatible with URL addresses but, at the same time, easily readable by a human.

Slugs are widely used in content management systems such as Wordpress and other CMS.

Slugify takes care of formatting the text strings, applying a series of rules that remove special characters, convert characters to lowercase, or replace spaces with hyphens.

How to use Slugify

To install “Slugify” in a .NET project, you can use the NuGet package manager. Open the NuGet package manager console and run the command

Install-Package Slugify

Now, using Slugify is very simple. We just have to use the ‘GenerateSlug’ method of the ‘SlugHelper’ class.

var text = "A useful example of a Slug";
var slug = new SlugHelper().GenerateSlug(text);

Console.WriteLine(slug); // output: a-useful-example-of-a-slug

Additionally, we can change the configuration used to create the Slug.

// Creating a configuration object
SlugHelper.Config config = new SlugHelper.Config();

// Replace spaces with a hyphen
config.CharacterReplacements.Add(" ", "-");

// We want a lowercase Slug
config.ForceLowerCase = true;

// Collapse consecutive whitespace chars into one
config.CollapseWhiteSpace = true;

var slugify = new SlugHelper(config);
var slug = new SlugHelper().GenerateSlug("whatever");

In short, a simple library that does its job correctly, and that will be very useful for generating slugs or URLs from an arbitrary string.

Stateless is Open Source, and all the code is available on GitHub - fcingolani/Slugify: Simple Slug / Clean URL generator helper for Microsoft .NET framework.