Created
December 10, 2014 16:13
-
-
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
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
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'),''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
exactly what I needed . thanks