Capitalize the first letter of a String in React

avatar

Borislav Hadzhiev

Mon May 02 20222 min read

banner

Photo by Syafrie Arvin

Capitalize the first letter of a String in React #

To capitalize the first letter of a string in React:

  1. Use the charAt() method to get the first letter of the string.
  2. Call the toUpperCase() method on the letter.
  3. Use the slice() method to get the rest of the string.
  4. Concatenate the results.
App.js
// 👇️ 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.

Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0, and the index of the last - string.length - 1.

Then we used the String.toUpperCase() method to uppercase the character at position 0.

App.js
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.

App.js
<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.

App.js
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.

App.js
export default function App() { const str = 'alice'; return ( <div> <h2>{str.charAt(0).toUpperCase() + str.slice(1)}</h2> </div> ); }
Use the search field on my Home Page to filter through my more than 1,000 articles.