Capitalize a string in JavaScript
This post will discuss how to capitalize a string in JavaScript.
There are several ways to convert the first letter of the string to uppercase. These are demonstrated below:
1. Using toUpperCase() method
The idea is to get the first character of the string and capitalize it using the toUpperCase() method. Then prepend it with the remaining string using the + operator. This method is demonstrated below using the slice() method:
|
1 2 3 4 5 6 7 |
var str = "hello"; const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalize(str)); /* Output: Hello */ |
Alternatively, you can use the substring() method to get the remaining string.
|
1 2 3 4 5 6 7 |
var str = "hello"; const capitalize = str => str.charAt(0).toUpperCase() + str.substring(1); console.log(capitalize(str)); /* Output: Hello */ |
You can also use the [] operator instead of the charAt() method.
|
1 2 3 4 5 6 7 |
var str = "hello"; const capitalize = str => str[0].toUpperCase() + str.substring(1); console.log(capitalize(str)); /* Output: Hello */ |
Another plausible way involves using the template literals, as shown below:
|
1 2 3 4 5 6 7 |
var str = "hello"; const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; console.log(capitalize(str)); /* Output: Hello */ |
2. Using Underscore.String.js
Underscore.string is an Underscore extension which has offers several utility functions for string manipulation. It has the _.capitalize method, which converts the first letter of the string to uppercase.
|
1 2 3 4 5 6 7 8 9 |
var _ = require('underscore.string'); var str = "hello"; str = _.capitalize(str); console.log(str); /* Output: Hello */ |
4. Using Lodash Library
Similar to the underscore.string library, lodash offers the _.capitalize method. It converts the first character of a string to upper case and the remaining character to lower case.
To avoid converting the remaining characters to lower case, you can use the _.upperFirst method.
|
1 2 3 4 5 6 7 8 9 |
var _ = require('lodash'); var str = "hello"; str = _.upperFirst(str); console.log(str); /* Output: Hello */ |
That’s all about capitalizing a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)