Capitalize the first letter of a string using 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
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.
1 2 3 4 | const str = "cluemediator"; const output = str.charAt(0).toUpperCase() + str.slice(1); console.log(output); // Output: Cluemediator |
You can also use the following code.
1 2 3 4 | 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.
1 2 3 4 | 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..!! 🙂