Skip to content

Instantly share code, notes, and snippets.

@lilmuckers
Last active September 25, 2017 08:38
Show Gist options
  • Save lilmuckers/5398242 to your computer and use it in GitHub Desktop.
Save lilmuckers/5398242 to your computer and use it in GitHub Desktop.
Javascript Slugify function.
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