Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Syafrie Arvin
To capitalize the first letter of a string in React:
charAt()
method to get the first letter of the string.toUpperCase()
method on the letter.slice()
method to get the rest of the string.// 👇️ if you need to capitalize first and lowercase rest const capitalizeFirstLowercaseRest = str => { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); }; export default function App() { // 👇️ if you only need to capitalize first letter const capitalizeFirst = str => { return str.charAt(0).toUpperCase() + str.slice(1); }; const str = 'alice'; console.log(capitalizeFirst(str)); // 👉️ "Alice" return ( <div> <h2>{capitalizeFirst(str)}</h2> </div> ); }
We created 2 reusable functions - capitalizeFirstLowercaseRest
and
capitalizeFirst
.
The capitalizeFirstLowercaseRest
function converts the first letter of a
string to uppercase and the rest to lowercase, whereas the capitalizeFirst
function simply converts the first letter of a string to uppercase.
The only parameter we passed to the String.charAt method is the index of the character we want to get.
0
, and the index of the last - string.length - 1
.Then we used the
String.toUpperCase()
method to uppercase the character at position 0
.
const capitalizeFirst = str => { return str.charAt(0).toUpperCase() + str.slice(1); };
We used the addition (+) operator to concatenate the first character with the rest of the string.
The only parameter we passed to the String.slice method is the start index - the index of the first character to be included in the new string.
Notice that we wrapped the call to the capitalizeFirst
function in curly
braces in our JSX code.
<h2>{capitalizeFirst(str)}</h2>
The curly braces mark the beginning of an expression that has to be evaluated.
If you only have to do this once in your code, you don't have to create a reusable function that capitalizes the first letter.
export default function App() { const str = 'alice'; const result = str.charAt(0).toUpperCase() + str.slice(1); console.log(result); // 👉️ "Alice" return ( <div> <h2>{result}</h2> </div> ); }
You could also do it directly in your JSX code.
export default function App() { const str = 'alice'; return ( <div> <h2>{str.charAt(0).toUpperCase() + str.slice(1)}</h2> </div> ); }