The _.capitalize() method is a part of the Lodash library and is used to format strings. It takes a string as input and returns a new string where the first character is uppercase and all other characters are lowercase. This method is commonly used when formatting user inputs or ensuring consistent text case.
Syntax
_.capitalize(string);
string: The string that you want to capitalize.
Let's start with a simple example of how the _.capitalize() method works.
To make the lodash library available in your project, the user must download it from the NPM with the help of the following command.
The variable Capital is assigned the string "Hello", which already has the first letter capitalized.
Applying _.capitalize() leaves the string unchanged as "Hello", since the first letter is uppercase and the rest are lowercase.
Features of lodash in JavaScript
Deep cloning: Lodash provides _.cloneDeep() to create a deep copy of an object or array, preserving nested structures.
Chaining: Lodash allows method chaining, enabling you to run multiple operations on a collection in a concise and readable manner with _.chain().
Debouncing: The _.debounce() method helps limit the rate at which a function is executed, perfect for handling events like scrolling or resizing.
Object manipulation: Lodash offers powerful utilities for working with objects, such as _.merge() for deep merging and _.get() for safely accessing nested properties.
Array operations: Functions like _.uniq() remove duplicate values, and _.groupBy() groups elements based on a criterion, making array manipulation efficient.
Conclusion
Lodash’s _.capitalize() method capitalizes the first letter of a string and converts the rest to lowercase, making it ideal for text formatting, standardizing user input, and ensuring consistent presentation in your app. It saves time and reduces errors compared to custom case transformation logic.