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\"
If you use underscore.js or Lo-Dash, the underscore.string library provides string extensions, including capitalize:
_.capitalize(string) Converts first letter of the string to uppercase.
Example:
_.capitalize("foo bar") == "Foo bar"
You can do it in one line like this
string[0].toUpperCase() + string.substring(1)
The ucfirst
function works if you do it like this.
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
Thanks J-P for the aclaration.
p::first-letter {
text-transform: uppercase;
}
%a
, this selector would apply to %
and as such a
would not be capitalized.:first-letter
).Since there are numerous answers, but none in ES2015 that would solve original problem efficiently, I came up with the following:
const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
parameters => function
is so called arrow function.capitalizeFirstChar
instead of capitalizeFirstLetter
, because OP didn't asked for code that capitalizes the first letter in the entire string, but the very first char (if it's letter, of course).const
gives us the ability to declare capitalizeFirstChar
as constant, which is desired since as a programmer you should always explicitly state your intentions.string.charAt(0)
and string[0]
. Note however, that string[0]
would be undefined
for empty string, so it should be rewritten to string && string[0]
, which is way too verbose, compared to the alternative.string.substring(1)
is faster than string.slice(1)
.Only because this is really a one liner I will include this answer. It's an ES6 based interpolated string one liner.
let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
Here's a more object-oriented approach:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
You'd call the function, like this:
"hello world".capitalize();
With the expected output being:
"Hello world"