Capitalize the first letter of a string using JavaScript
๐
February 18, 2022
๐JavaScript
In this JavaScript article, we will show you how to capitalize the first letter of a string using JavaScript. There are many ways to uppercase the first letter of a string in JavaScript but we will look at two of them.
Checkout more articles on JavaScript
- How to create an auto-resize Textarea in JavaScript
- Scroll to a specific element using JavaScript
- Convert a 12 hour format to 24 hour format using JavaScript
- Convert the local time to another timezone using JavaScript
- Rest Parameters in JavaScript
Methods to capitalize the first letter of a string
1. Using charAt() and slice()
In the first method, we will use the following functions and concat a string.
- `charAt()` - This function returns the character at a given position in the string.
- `slice()` - This function extracts a section of a string and returns it as a new string, without modifying the original string.
const str = "cluemediator";
const output = str.charAt(0).toUpperCase() + str.slice(1);
console.log(output);
// Output: Cluemediator
You can also use the following code.
const str = "cluemediator";
const output = str[0].toUpperCase() + str.slice(1);
console.log(output);
// Output: Cluemediator
2. Using regular expression
Letโs use the Regular Expression to make the first letter of a string in uppercase.
const str = "cluemediator";
const output = str.replace(/^./, str[0].toUpperCase());
console.log(output);
// Output: Cluemediator
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐