Easy slug generation with Slugity

Posted on Friday, 18th March 2016

This year, as outlined in my goals for 2016 post, I’ve been keen to turn random bits of code I’ve written across a variety of projects, into fully-fledged open-sourced libraries that can be downloaded via NuGet. My first library aims to tackle a minor problem any developer that works on public facing web-based applications faces - generating search engine friendly URL slugs.

Introducing Slugity - The highly configurable C# slug generator

Whilst creating Slugity, my main focus was configure-ability. People, myself included, have opinions on how a URL should be formatted. Some people like the camel-case URLs that frameworks such as ASP.NET MVC encourage, other dogmatically favour lowercase slugs. Some people still like to strip stop-words from their slugs in order to shorten the overall URL length whilst retaining keyword density within their slugs. Having jumped from pattern to pattern across a variety of projects myself, I was keen to develop Slugity to cater to these needs.

Having been working on Slugity for a number of days now, below are the configuration end-points included in its first release:

  • Customisable slug text case (CamelCase, LowerCase, Ignore)
  • String Separator
  • Slug’s maximum length
  • Optional replacement characters
  • Stop Words

Slugity setup and configuring

Given the fact that slugs aren’t the most complicated strings to get right, setting up Slugity is a breeze. It comes with a default configuration that should be suitable for the majority of its users, myself includes - but it’s simple enough to configure if the default settings don’t meet your requirements.

Using default configuration options:

var slugity = new Slugity();
string slug = slugity.GenerateSlug("A <span style="font-weight: bold">customisable</a> slug generation library");

Console.Log(slug); 
//Output: a-customisable-slug-generation-library

Configuring Slugity:

If Slugity’s default configuration doesn’t meet your requirements then configuration is easy:

var configuration = new SlugityConfig
{
    TextCase = TextCase.LowerCase,
    StringSeparator = '_',
    MaxLength = 60
};

configuration.ReplacementCharacters.Add("eat", "munch on");

var slugity = new Slugity(configuration);
string slug = slugity.GenerateSlug("I like to eat lettuce");

Console.Log(slug);
//Output: i_like_to_munch_on_lettuce

Moving forward I’d like to add the ability to replace the various formatting classes that are responsible for the various formatting and cleaning of the slug.

The code is currently up on GitHub and can be viewed here. I’m in the process of finishing off the last bits and pieces and then getting it added to NuGet, so stay tuned.

Update

The library has recently been added to NuGet and can be downloaded here, or via the following NuGet command:

Install-Package Slugity