Skip to content

Instantly share code, notes, and snippets.

@Jamiewarb
Forked from mathewbyrne/slugify.js
Last active March 28, 2019 16:33
Show Gist options
  • Save Jamiewarb/2b9c94fb46f509693bc8b91ef923ab78 to your computer and use it in GitHub Desktop.
Save Jamiewarb/2b9c94fb46f509693bc8b91ef923ab78 to your computer and use it in GitHub Desktop.
Javascript Slugify
function slugify(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
}
function slugify($string) {
$string = strtolower($string);
$string = preg_replace('/\s+/', '-', $string); // Replace spaces with -
$string = preg_replace('/[^\w\-]+/', '', $string); // Remove all non-word chars
$string = preg_replace('/\-\-+/', '-', $string); // Replace multiple - with single -
$string = preg_replace('/^-+/', '', $string); // Trim - from start of text
$string = preg_replace('/-+$/', '', $string); // Trim - from end of text
return preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment