Uppercase the First Letter in a String with JavaScript
Capitalizing the first letter of a string is a common task in programming.
Fortunately, JavaScript provides several ways to achieve this task.
Here are a few handy ways in case you are stuck. 👇
Method 1:
Using the charAt()
method and the toUpperCase()
method.
The charAt()
method retrieves the character at a specified index in a string, while the toUpperCase()
method converts a string to uppercase.
Here's an example of how to use these methods together:
let str = "hello world"; let capitalizedStr = str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalizedStr); // "Hello world"
Method 2
Using the slice()
and toUpperCase()
methods.
Another way to capitalize the first letter of a string in JavaScript is by using the slice()
method and the toUpperCase()
method.
The slice()
method extracts a portion of a string and returns it as a new string, while the toUpperCase()
method converts the first letter of the string to uppercase.
Here's an example of how to use these methods together:
let str = "hello world"; let capitalizedStr = str.slice(0, 1).toUpperCase() + str.slice(1); console.log(capitalizedStr); // "Hello world"
Method 3
Using regular expressions and the replace()
method
You'll rarely find a string problem you can't solve with a regular expression. Here's another one.
Regular expressions are patterns used to match character combinations in strings, while the replace()
method replaces a specified value with another value in a string.
Here's an example of how to use regular expressions and the replace()
method:
let str = "hello world"; let capitalizedStr = str.replace(/^\w/, c => c.toUpperCase()); console.log(capitalizedStr); // "Hello world"
The value of the first character in str is matched using the regular expression /^\w/
(which matches the first-word character in the string), then converts the first character to uppercase using an arrow function in the replace()
method.
Hopefully this can help you out if you get stuck with this problem!