How to capitalize the first letter in JavaScript
The utility function below should do the capitalization of the first letter. But if you are dealing with internationalization you may need to find better alternatives.
function capitalizeFirstLetter(string) {
return string.slice(0, 1).toUpperCase() + string.slice(1);
}
capitalizeFirstLetter('hey'); // returns 'Hey'
How does it work?
- The
string.slice(0, 1)
code extracts the first character. - The
.toUpperCase()
converts the first character to upper case. - The
string.slice(1)
returns the initial string except the first character. - Everything is concatenated with the
+
operator.
You could also do string.chartAt(0)
instead of string.slice(0,1)
.
Questions
What's the function f output?
function f(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
f('hello');
What's the function f output?
function f(string) {
return string.slice(0, 1).toUpperCase() + string.slice(1);
}
f('hello');