Home > Software design >  how to capitalize first letter after "."
how to capitalize first letter after "."

Time:10-16

I wrote this function for it :

const [text, setText] = useState('');

const capitalizeClick =()=>{
        var str = text.split(".") ;
        let newText = str.map((arr)=>(arr[0].toUpperCase()));
        setText(newText)

        
    }
     return(
       <textarea className="form-control" value={text} onChange={handleOnChange}  id="myBox" rows={15}  />
             
    )

but i am geting this error : Cannot read properties of undefined (reading 'toUpperCase')

CodePudding user response:

You need to accept text as an argument to the function.

const capitalizeClick = (text)=> {
        var str = text.split(".") ;
        let newText = str.map((arr)=>((arr[0]).toUpperCase));
        setText(newText)
}

CodePudding user response:

You can do with a simple regex. This will capitalize all first letters after each .

const capitalizeText = text => text?.replace(/\.(.)/g, letter => letter.toUpperCase())
capitalizeText("This.is.a.test")

This.Is.A.Test

To modify it to do only once, just remove the global modifier.

const capitalizeText = text => text?.replace(/\.(.)/, letter => letter.toUpperCase())
capitalizeText("This.is.a.test")

This.Is.a.test

CodePudding user response:

Using split, map and join probably

  • Related