Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash title case (uppercase first letter of every word)

People also ask

What is startCase in Lodash?

Return Value: This method returns the start of the case string. Below example illustrate the Lodash _. startCase() method in JavaScript: Example 1: Javascript.

How do you capitalize a string in JavaScript?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do I use Lodash library?

Now in order to use the Lodash library, you need to require it in the code file. const _ = require("lodash"); Now let's understand how to use Lodash with the help of the code example. Example: In this example, we will simply create an empty string using the lodash _.


This can be done with a small modification of startCase:

_.startCase(_.toLower(str));

console.log(_.startCase(_.toLower("This string ShouLD be ALL in title CASe")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

_.startCase(_.camelCase(str))

For non-user-generated text, this handles more cases than the accepted answer

> startCase(camelCase('myString'))
'My String'
> startCase(camelCase('my_string'))
'My String'
> startCase(camelCase('MY_STRING'))
'My String'
> startCase(camelCase('my string'))
'My String'
> startCase(camelCase('My string'))
'My String'

with lodash version 4.

_.upperFirst(_.toLower(str))


'This string ShouLD be ALL in title CASe'
  .split(' ')
  .map(_.capitalize)
  .join(' ');

There are mixed answers to this question. Some are recommending using _.upperFirst while some recommending _.startCase.

Know the difference between them.

i) _.upperFirst will transform the first letter of your string, then string might be of a single word or multiple words but the only first letter of your string is transformed to uppercase.

_.upperFirst('jon doe')

output:

Jon doe

check the documentation https://lodash.com/docs/4.17.10#upperFirst

ii) _.startCase will transform the first letter of every word inside your string.

_.startCase('jon doe')

output:

Jon Doe

https://lodash.com/docs/4.17.10#startCase


That's the cleanest & most flexible implementation imo from testing it on my own use cases.

import { capitalize, map } from "lodash";

const titleCase = (str) => map(str.split(" "), capitalize).join(" ");

// titleCase("ALFRED NÚÑEZ") => "Alfred Núñez"
// titleCase("alfred núñez") => "Alfred Núñez"
// titleCase("AlFReD nÚñEZ") => "Alfred Núñez"
// titleCase("-") => "-"

Here's a way using ONLY lodash methods and no builtin methods:

_.reduce(_.map(_.split("Hello everyOne IN the WOrld", " "), _.capitalize), (a, b) => a + " " + b)