Open In App

How to Capitalize the First Letter of a String Using Lodash?

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Capitalizing the first letter of a string consists of transforming only the initial character to uppercase while keeping the rest of the string in its original case.

Below are the possible approaches to Capitalize the First Letter of a String Using Lodash:

Run the below command to install Loadash JavaScript Library:

npm install loadash

Using _.capitalize() Method

In this approach, we are using Lodash's _.capitalize() Method to capitalize the first letter of a string and convert the remaining characters to lowercase. This function simplifies the process by directly transforming the string in one step. For example, it converts 'geeksforgeeks' to 'Geeksforgeeks'.

Syntax:

_.capitalize(string)

Example: The below example uses the _.capitalize() function to capitalize the first letter of a string using Lodash.

JavaScript
const _ = require('lodash');
let str = 'geeksforgeeks';
str = _.capitalize(str);
console.log(str); 

Output:

Geeksforgeeks

Using _.upperFirst() with _.lowerCase() Method

In this approach, we are using _.lowerCase() to convert the entire string to lowercase and then _.upperFirst() to capitalize the first letter of the resulting string. This method makes sure that only the first letter is uppercase while the rest are lowercase.

Syntax:

_.upperFirst(_.lowerCase(string))

Example: The below example uses the _.upperFirst() with _.lowerCase() functions to capitalize the first letter of a string using Lodash.

JavaScript
const _ = require('lodash');
let str = 'geeksforgeeks';
str = _.upperFirst(_.lowerCase(str));
console.log(str);

Output:

Geeksforgeeks

Using _.startCase() with _.camelCase() Method

In this approach, we are using _.camelCase() to convert the string into camel case format, where the first word is lowercase and subsequent words are capitalized. We then apply _.startCase() to transform it into a format where the first letter of each word is capitalized.

Syntax:

_.startCase(_.camelCase(string))

Example: The below example uses the _.startCase() with _.camelCase() functions to capitalize the first letter of a string using Lodash.

JavaScript
const _ = require('lodash');
let str = 'geeksforgeeks';
str = _.startCase(_.camelCase(str));
console.log(str);

Output:

Geeksforgeeks

Next Article

Similar Reads