Last active
September 25, 2017 08:38
-
-
Save lilmuckers/5398242 to your computer and use it in GitHub Desktop.
Javascript Slugify function.
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
String.prototype.slugify = function() | |
{ | |
var p = ['.', '=', '-']; | |
var s = '-'; | |
//now we need to do some fiddling with special characters | |
var replaceArray = { | |
'a': /à|á|å|â/, | |
'e': /è|é|ê|ẽ|ë/, | |
'i': /ì|í|î/, | |
'o': /ò|ó|ô|ø/, | |
'u': /ù|ú|ů|û/, | |
'c': /ç/, | |
'n': /ñ/, | |
'ae': /ä|æ/, | |
'oe': /ö/, | |
'ue': /ü/, | |
'Ae': /Ä/, | |
'Ue': /Ü/, | |
'Oe': /Ö/, | |
'ss': /ß/, | |
'and': /&/ | |
} | |
var string = this; | |
//replace the strings | |
for(var k in replaceArray){ | |
string = string.replace(replaceArray[k], k); | |
} | |
return string.toLowerCase(). | |
replace(new RegExp('[' + p.join('') + ']', 'g'), ' '). // replace preserved characters with spaces | |
replace(/-{2,}/g, ' '). // remove duplicate spaces | |
replace(/^\s\s*/, '').replace(/\s\s*$/, ''). // trim both sides of string | |
replace(/[^\w\ ]/gi, ''). // replaces all non-alphanumeric with empty string | |
replace(/ /gi, ' '). | |
replace(/[\ ]/gi, s); // Convert spaces to dashes | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment