Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript Slug Generator
// Generates a URL-friendly "slug" from a provided string.
// For example: "This Is Great!!!" transforms into "this-is-great"
function generateSlug (value) {
// 1) convert to lowercase
// 2) remove dashes and pluses
// 3) replace spaces with dashes
// 4) remove everything but alphanumeric characters and dashes
return value.toLowerCase().replace(/-+/g, '').replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
};
@pid

This comment has been minimized.

Copy link

commented Jul 2, 2013

take a look to http://pid.github.io/speakingurl/ slugify with a lot of options ;-)

@lerouxb

This comment has been minimized.

Copy link

commented May 2, 2014

Just a heads-up: You should probably swap steps 3 and 4, otherwise you can end up with more consecutive dashes again after stripping some characters. Step 2 is probably superfluous given the steps that follow.

@vluzrmos

This comment has been minimized.

Copy link

commented Jun 8, 2017

thanks @pid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.