Last active
August 23, 2019 08:00
-
-
Save utilmind/a13f06e73fcc9803632ed9f7100c7675 to your computer and use it in GitHub Desktop.
ucwords() for JavaScript
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
// The unicode-safe ucwords() func for JS (to capitalize the first characters of words), | |
// which additionally respects double-lastnames like Russian Засс-Ранцев and weird French names, | |
// like Honoré de Balzac and d'Artagnan. | |
String.prototype.ucwords = function() { | |
return this.toLowerCase() | |
.replace(/(^|\s|\-)[^\s$]/g, function(m) { | |
return m.toUpperCase(); | |
}) | |
// French, Arabic and some noble names... | |
.replace(/\s(Of|De|Van|Von|Ibn|Из|Ван|Фон|Ибн)\s/g, function(m) { // Honoré de Balzac, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd etc. | |
return m.toLowerCase(); | |
}) | |
.replace(/(^|\s)(D|Д)(['’][^\s$])/g, function(m, p1, p2, p3) { // D'Artagnan or d'Artagnan / Д’Артаньян или д’Артаньян | |
return p1 + (p1 === "" ? p2/*.toUpperCase()*/ : p2.toLowerCase()) + p3.toUpperCase(); | |
}); | |
} | |
// Usage (best if used together with "text-transform: capitalize"): | |
// <input onBlur="this.value = this.value.ucwords()" style="text-transform: capitalize" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment