Last active
July 20, 2018 14:01
-
-
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
This file contains hidden or 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
/** | |
* 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; | |
}; |
This file contains hidden or 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
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