To capitalize the first letter of a string in JavaScript:
- Use the
charAt()
function to isolate and uppercase the first character from the left of the string. - Use the
slice()
method to slice the string leaving the first character. - Concatenate the output of both functions to form a capitalized string.
const phrase = 'example'
const output = phrase.charAt(0).toUpperCase() + phrase.slice(1)
console.log(output)
// Example
Alternatively, you can use the use replace()
method with regular expressions to capitalize a string:
const phrase = 'example'
const output = phrase.replace(/^\w/, c => c.toUpperCase())
console.log(output)
// Example
You can even take one step further and create a function to transform the first character of the string to uppercase:
const capitalize = str => {
if (typeof str === 'string') {
return str.replace(/^\w/, c => c.toUpperCase())
} else {
return ''
}
}
The above capitalize()
function also checks the type of the passed parameter. If it is not a string, it returns an empty string.
Now just call the function whenever you want to capitalize a string:
capitalize('google') // Google
capitalize('how it works') // How it works
capitalize('a') // A
capitalize([]) // ''
capitalize() // ''
If you want to capitalize all words of a paragraph on a web page, use CSS text-transform
property instead:
.capitalize {
text-transform: capitalize;
}
Now just add the capitalize
class to your HTML paragraph element as shown below:
<p class="capitalize">Welcome to JavaScript tutorials!</p>
Read Next: Capitalize the first letter of each word in a string using JavaScript
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.