I have data that is in all caps. I want to make the first letter of each word capitalized and the rest of the word lowercase but I cannot seem to do it.
I tried this using lodash
{
Header: 'Security Name',
accessor: 'securityName',
minWidth: 70, // minWidth is only used as a limit for resizing
width: 260, // width is used for both the flex-basis and flex-grow
maxWidth: 300,
Cell: e => <div>{_.lowerCase.firstUpper(e.value)} </div>,
},
But it won't work. Any ideas on how to make this possible?
CodePudding user response:
const capitalize = (e) => {
const lower = e.value.toLowerCase();
return lower.replace(/(^|\s)[a-z]/g, (match) => match.toUpperCase());
}
{
Header: 'Security Name',
accessor: 'securityName',
minWidth: 70, // minWidth is only used as a limit for resizing
width: 260, // width is used for both the flex-basis and flex-grow
maxWidth: 300,
Cell: e => <div>{capitalize(e)} </div>,
},
The replace() method takes two arguments: a regular expression (regex) that matches the first letter of each word, and a function that returns the uppercase version of the matched letter. The regex /(^|\s)[a-z]/g matches the first letter of each word, whether it occurs at the beginning of the string (^) or after a whitespace character (\s). The g flag at the end of the regex makes the match global, so that all occurrences of the pattern are replaced.
CodePudding user response:
The reaosn why your code did not work is because the method is not firstUpper but upperFirst.
Also, you need to write _.lowerCase(_.upperFirst(e.value))
instead of _.lowerCase.upperFirst(e.value)
, because JavaScript methods take parenthesis to initiate.
However, the better solution will be using capitalized directly, which is also provided by lodash .
// Example
_.capitalize('FRED');
// => 'Fred'