Skip to content

Instantly share code, notes, and snippets.

@4lun
Created December 10, 2014 16:13
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save 4lun/c92affc5ef53cab047dd to your computer and use it in GitHub Desktop.
Save 4lun/c92affc5ef53cab047dd to your computer and use it in GitHub Desktop.
Slug function in JS matching the Laravel 4 implementation (Str::slug) - Note: does not include the transliteration of a UTF-8 value to ASCII
function slug(title, separator) {
if(typeof separator == 'undefined') separator = '-';
// Convert all dashes/underscores into separator
var flip = separator == '-' ? '_' : '-';
title = title.replace(flip, separator);
// Remove all characters that are not the separator, letters, numbers, or whitespace.
title = title.toLowerCase()
.replace(new RegExp('[^a-z0-9' + separator + '\\s]', 'g'), '');
// Replace all separator characters and whitespace by a single separator
title = title.replace(new RegExp('[' + separator + '\\s]+', 'g'), separator);
return title.replace(new RegExp('^[' + separator + '\\s]+|[' + separator + '\\s]+$', 'g'),'');
}
Copy link

ghost commented Oct 30, 2018

Thanks,

@lx-berlin
Copy link

exactly what I needed . thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment