To capitalize the first letter of a string in React, you can create a function that modifies the string by uppercasing the first character and then combining it with the rest of the string. Here’s how you can do it:
import React from 'react';
function CapitalizeFirstLetter() {
const capitalizeFirstLetter = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
const originalString = "hello world";
const capitalizedString = capitalizeFirstLetter(originalString);
return (
<div>
<p>Original String: {originalString}</p>
<p>Capitalized String: {capitalizedString}</p>
</div>
);
}
export default CapitalizeFirstLetter;
In this example, the CapitalizeFirstLetter
component defines the capitalizeFirstLetter
function, which takes a string as input. It extracts the first character using charAt(0)
and then uses the toUpperCase()
method to convert it to uppercase. The slice(1)
method is used to extract the rest of the string.
The component then applies the capitalizeFirstLetter
function to the originalString
and displays both the original and capitalized versions of the string.
Replace "hello world"
with your own string, and the component will display both the original and capitalized versions of it.
Keep in mind that the capitalizeFirstLetter
function only capitalizes the first letter of the string and leaves the rest unchanged.