How to capitalize the first letter of a word using JavaScript for the novice developer
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:
- The DOM in JavaScript, jQuery, AngularJS, and React (Lynda.com).
- The DOM in JavaScript, jQuery, AngularJS, and React (LinkedIn)
- Building JSF Web Applications with Java EE 7 (Lynda.com)
- Building JSF Web Applications with Java EE 7 (LinkedIn)
- Troubleshooting Vue.js (packtpub.com).
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