How do I make the first letter of a string uppercase, but not change the case of any of the other letters?
For example:
\"this is a test\"
Use:
var str = "ruby java";
console.log(str.charAt(0).toUpperCase() + str.substring(1));
It will output "Ruby java"
to the console.
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'
We could get the first character with one of my favorite RegExp
, looks like a cute smiley: /^./
String.prototype.capitalize = function () {
return this.replace(/^./, function (match) {
return match.toUpperCase();
});
};
And for all coffee-junkies:
String::capitalize = ->
@replace /^./, (match) ->
match.toUpperCase()
...and for all guys who think that there's a better way of doing this, without extending native prototypes:
var capitalize = function (input) {
return input.replace(/^./, function (match) {
return match.toUpperCase();
});
};
For another case I need it to capitalize the first letter and lowercase the rest. The following cases made me change this function:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
Checkout this solution:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master
The basic solution is:
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
console.log(capitalizeFirstLetter('foo')); // Foo
Some other answers modify String.prototype
(this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the prototype
and could cause conflicts if other code uses the same name / a browser adds a native function with that same name in future).
...and then, there is so much more to this question when you consider internationalisation, as this astonishingly good answer (buried below) shows.
If you want to work with Unicode code points instead of code units (for example to handle Unicode characters outside of the Basic Multilingual Plane) you can leverage the fact that String#[@iterator]
works with code points, and you can use toLocaleUpperCase
to get locale-correct uppercasing: