Created
September 20, 2021 16:22
-
-
Save mitchbudreski/0f87b51d8ace2aa2d08e814c1cbd3635 to your computer and use it in GitHub Desktop.
Urlify - Pretty URL slugs without EncodeURI functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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