How to Capitalize first letter of String in JavaScript
Table of Contents
Needing to capitalize the first letter of a string is a common task in JavaScript.
Thankfully, there are many ways to do this, some methods better than others.
In this post, we'll learn how to capitalize the first letter of a string.
Capitalizing the first letter of a string
The most simple way to accomplish this is to use a combination of the charAt()
and toUpperCase()
methods.
We use the charAt()
method to get the first letter of a string, then we use the toUpperCase()
method to capitalize it.
That looks like this:
JAVASCRIPTconst string = "hello world";
const firstLetter = string.charAt(0);
const capitalizedFirstLetter = firstLetter.toUpperCase(); // "H"
Great, now that we've been able to capitalize the first letter of a string, we just need to add it to the rest of the string.
You can get the rest of the string by using the slice()
method.
JAVASCRIPTconst string = "hello world";
const restOfString = string.slice(1); // "ello world"
Now that we can get the first letter capitalized and the rest of the string, we can combine them together.
JAVASCRIPTconst string = "hello world";
const firstLetter = string.charAt(0);
const capitalizedFirstLetter = firstLetter.toUpperCase(); // "H"
const restOfString = string.slice(1); // "ello world"
const capitalizedString = capitalizedFirstLetter + restOfString; // "Hello world"
Thankfully, we can simply this greatly into a one-liner
JAVASCRIPTconst string = "hello world";
const capitalizedString = string.charAt(0).toUpperCase() + string.slice(1); // "Hello world"
We can also turn this into a function for reusability.
JAVASCRIPTconst capitalize = string => string.charAt(0).toUpperCase() + string.slice(1);
const capitalizedString = capitalize("hello world"); // "Hello world"
Conclusion
In this post, we learned how to capitalize the first letter of a string.
We were able to accomplish this using a combination of the charAt()
and toUpperCase()
methods, and we wrote a standalone function for reusability.
Hope you've found this content helpful. Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor