How To Convert Every First Character Of The String To Uppercase In Javascript

Hello developers, In this blog we are going to make a function that converts every first character of the string to uppercase

First, create a new app using the following command

npx create-react-app new-app

Then, open the App.js file and paste the below code :

import React, { useState } from 'react'
import { Button, Box } from '@mui/material'

const Capitalize = () => {
    const [value, setValue] = useState('')
    const capitalize = () => {
        if (!value) throw 'Cannot capilatize undefined';    //If value is empty or null or undefined this will throws an error

        let strings = value.split(' ');                     // we just split our string from spaces and make an array from it

        strings = strings.map(string => string.charAt(0).toLocaleUpperCase() + string.slice(1)).join(' ');
        //then we loop over the string array and finds each first character from strings and converts to uppercase and joined it
        setValue(strings)
    }
    return (
        <Box display='flex' flexDirection='column' alignItems='center'>
            <input type="text" onChange={(e) => setValue(e.target.value)} />
            <Button onClick={() => capitalize()}> Capitalize</Button>
            {value}
        </Box>
    )
}

export default Capitalize

That’s it this function converts every first character of the string to uppercase

Demo:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories