Comment faire la première lettre d'une majuscule en JavaScript

Mots clés : javascriptstringlettercapitalizejavascript

meilleur 5 Réponses Comment faire la première lettre d'une majuscule en JavaScript

vote vote

95

function capitalizeFirstLetter(string) {   return string.charAt(0).toUpperCase() + string.slice(1); }  console.log(capitalizeFirstLetter('foo')); // Foo
const capitalizeFirstLetter = ([ first, ...rest ], locale = navigator.language) =>   first.toLocaleUpperCase(locale) + rest.join('')  console.log(   capitalizeFirstLetter('foo'), // Foo   capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"), // "𐐎𐐲𐑌𐐼𐐲𐑉" (correct!)   capitalizeFirstLetter("italya", 'tr') // İtalya" (correct in Turkish Latin!) )
vote vote

87

Object.defineProperty(String.prototype, 'capitalize', {   value: function() {     return this.charAt(0).toUpperCase() + this.slice(1);   },   enumerable: false }); 
"hello, world!".capitalize(); 
"Hello, world!" 
vote vote

71

p:first-letter {     text-transform:capitalize; } 
vote vote

63

function capitalize(s) {     return s[0].toUpperCase() + s.slice(1); } 
function capitalize(s) {     return s && s[0].toUpperCase() + s.slice(1); } 
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)  // to always return type string event when s may be falsy other than empty-string const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || "" 
vote vote

55

// 10,889,187 operations/sec function capitalizeFirstLetter(string) {     return string[0].toUpperCase() + string.slice(1); }  // 10,875,535 operations/sec function capitalizeFirstLetter(string) {     return string.charAt(0).toUpperCase() + string.slice(1); }  // 4,632,536 operations/sec function capitalizeFirstLetter(string) {     return string.replace(/^./, string[0].toUpperCase()); }  // 1,977,828 operations/sec String.prototype.capitalizeFirstLetter = function() {     return this.charAt(0).toUpperCase() + this.slice(1); } 

Questions similaires