Skip to content

Instantly share code, notes, and snippets.

@mitchbudreski
Created September 20, 2021 16:22
Show Gist options
  • Save mitchbudreski/0f87b51d8ace2aa2d08e814c1cbd3635 to your computer and use it in GitHub Desktop.
Save mitchbudreski/0f87b51d8ace2aa2d08e814c1cbd3635 to your computer and use it in GitHub Desktop.
Urlify - Pretty URL slugs without EncodeURI functions
//the function
export function urlify(text) {
return text
.toString()
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
//the output
const TestSlug = 'Mitch is testing a slug !!###';
urlify(TestSlug) = 'mitch-is-testing-a-slug'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment