Syntax, Parameter and Return Value
Syntax:
_.capitalize([string=''])
Parameters:
[string=''] (string): The string to capitalize.
Return Value:
(string) - Returns the capitalized string.
Examples
Capitalizing a Regular String:
JavaScript
var _ = require('lodash');
var text = 'hello world';
console.log(_.capitalize(text));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Hello world'
Demonstrates basic usage of capitalizing the first letter of a string.
Capitalizing Names:
JavaScript
var name = 'john doe';
console.log(_.capitalize(name));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'John doe'
Shows capitalizing the first letter of a name.
Handling Strings with Leading Spaces:
JavaScript
var title = ' lorem ipsum';
console.log(_.capitalize(title));

You can also try this code with Online Javascript Compiler
Run Code
Output:
' lorem ipsum'
An example of how _.capitalize() handles strings with leading spaces.
Standardizing User Input:
JavaScript
var userInput = 'tODAY Is a great DAY!';
console.log(_.capitalize(userInput));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Today is a great day!'
Demonstrates standardizing user input to start with a capital letter and the rest in lowercase.
Frequently Asked Questions
How does _.capitalize() handle non-alphabetic characters?
_.capitalize() will capitalize the first alphabetic character encountered and lowercase the rest. Non-alphabetic characters at the beginning of the string are left unchanged.
Can _.capitalize() be used for each word in a string?
_.capitalize() only capitalizes the first letter of the entire string. To capitalize each word, you would need to split the string into words and apply _.capitalize() to each word individually.
Does _.capitalize() affect the case of letters other than the first one?
Yes, all characters other than the first one are converted to lowercase by _.capitalize().
Conclusion
Lodash's _.capitalize() method is a useful tool for formatting strings such that only the first character is capitalized, and the rest are in lowercase. It's particularly beneficial for text presentation in user interfaces and standardizing user input.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.