Given a string, the task is to make the first letter of string uppercase in JavaScript.
Examples
Input: str = "hello world!"
Output: Hello world
Input: str = "welcome"
Output: Welcome
There are multiple approaches to make the first letter of a string to uppercase in JavaScript. We will explain each approaches with a detailed description and complete code examples.
Approach 1: Using charAt() and toUpperCase() Methods
One approach is to use the charAt()
method to extract the first character of the string, convert it to uppercase using the toUpperCase()
method, and then concatenate it with the rest of the string.
const str = "hello, world!"; const capitalizedStr = str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalizedStr); // Output: Hello, world!
Approach 2: Using substring() and toUpperCase() Methods
You can use the substring()
method to extract the first character of the string, convert it to uppercase using toUpperCase()
, and concatenate it with the substring starting from the second character.
const str = "hello, world!"; const capitalizedStr = str.substring(0, 1).toUpperCase() + str.substring(1); console.log(capitalizedStr); // Output: Hello, world!
Approach 3: Using ES6 String Interpolation
With ES6 template literals, you can directly interpolate the first character of the string into an interpolated template string, converting it to uppercase.
const str = "hello, world!"; const capitalizedStr = `${str.charAt(0).toUpperCase()}${str.slice(1)}`; console.log(capitalizedStr); // Output: Hello, world!
Approach 4: Using Regular Expression
Regular expressions provide powerful pattern matching capabilities in JavaScript. You can use a regular expression to replace the first character of the string with its uppercase equivalent.
const str = "hello, world!"; const capitalizedStr = str.replace(/^\w/, (c) => c.toUpperCase()); console.log(capitalizedStr); // Output: Hello, world!
Approach 5: Using split() and join() Methods
Another approach is to split the string into an array of characters, capitalize the first character using toUpperCase()
, and then join the array back into a string.
const str = "hello, world!"; const capitalizedStr = str.split("")[0].toUpperCase() + str.slice(1); console.log(capitalizedStr); // Output: Hello, world!