Skip to content

Instantly share code, notes, and snippets.

@rseon
Last active July 20, 2018 14:01
Show Gist options
  • Save rseon/26325fed510793cdd9cde92176401620 to your computer and use it in GitHub Desktop.
Save rseon/26325fed510793cdd9cde92176401620 to your computer and use it in GitHub Desktop.
Sluggify a string replacing spaces by "-", lowercasing and replacing accents and removing special chars
/**
* Sluggify a string replacing spaces by "-", lowercasing and replacing accents and removing special chars.
*
* @type {Function}
* @return {String}
*/
String.prototype.slug = String.prototype.slug || function() {
var replace = this.replace(/\s/g, '-');
replace = replace.toLowerCase();
// Replace accents and special chars
var base_chars = [
'1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'-', '_', ' '
];
replace = replace.normalize('NFKD').split('').map(function(c) {
return base_chars.find(function(bc) {
return bc.localeCompare(c, 'en', {
sensitivity: 'base'
}) == 0;
});
}).join('');
return replace;
};
console.log('It\'s co0l : ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž Then : @()[]<>§:!/.?\\=+°0123456789²^¨$£¤%*µ'.slug());
// Returns : "its-co0l--aaaaaaaaaaaaoooooooooooooeeeeeeeedccdiiiiiiiiuuuuuuuunnssyyyzz-then--01234567892 "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment