How to capitalize the first letter of a word using JavaScript for the novice developer

Christian Hur
1 min readNov 3, 2018

--

There are several ways to format a string but most common ones involve the handling of capitalization. The follow two cases format a string using the infamous string methods: “replace()”, “toLowerCase()”, and “toUpperCase()”.

Case 1: Capitalize only the first character of a string

This one is pretty obvious.

let str = "this Is A StrinG!";let newstr = str.replace(  /^[a-z]{1}/igm,function(m){return m.toUpperCase()});//Output:  This Is A StrinG!

Case 2: Capitalize only the first character and force the rest of string to be in lowercase

let str = "this Is A StrinG!let newstr = str.toLowerCase().replace(/^[a-z]{1}/igm,function(m){return m.toUpperCase()});//Output:  This is a string!

Try it here:

Note: You can omit the {1} as the default will only match the first character, but it’s there to guarantee that you only want one letter. If you want the first two characters, then replace it with {2}, etc.

Hope this helps. Happy coding!

My online training courses:

My book “Developing Business Applications for the Web: With HTML, CSS, JSP, PHP, ASP.NET, and JavaScript” is available on Amazon and MC Press.

Check out my author page at http://amazon.com/author/christianhur

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response