First to clarify, there's no such thing as lodash without javascript.
Now that that's cleared up, try this on for size:
_.map(_.split('DIGITAL & TECHNOLOGY', /\s+/), _.capitalize).join(' ')
This splits up the words between arbitrary amounts of space, maps each one to capitalize, and rejoins them into a string (you'll notice that calling capitalize
on just the ampersand is safe).
EDIT: I wanted to see if I could make this more reusable by turning the above statement into a function with just lodash. Here's what I came up with:
const split = _.partialRight(_.split, /\s+/)
, map = _.partialRight(_.map, _.capitalize)
, join = _.partialRight(_.join, ' ');
const mycapitalize = _.flow([split, map, join]);
mycapitalize('DIGITAL & TECHNOLOGY'); // => "Digital & Technology"
I like this approach because it semantically lays out the steps taken to process the string (i.e. first you split it, then you map it, then you join it). Here it is as "one-liner" if that's your thing:
const mycapitalize = _.flow([
_.partialRight(_.split, /\s+/)
, _.partialRight(_.map, _.capitalize)
, _.partialRight(_.join, ' ')
]);
mycapitalize('DIGITAL & TECHNOLOGY'); // => "Digital & Technology"
jsfiddle demo
Just to elaborate on what I did here: partialRight
is kind of like a special call to bind
. It partially applies the function (which is basically a way to say that it returns the function with one of the arguments hard coded). Conventionally, partial
methods apply arguments in order, so partialRight
applies them in reverse order (i.e. if a function has two parameters, partial
would "hard code" the first one while partialRight
would "hard code" the second/ last one). For example, _.split
takes two arguments, which are, in order, a string to split and a pattern to split it up by. _.partial(_.split, 'foo bar')
gives a function that takes a pattern to split up "foo bar"
on, while _.partialRight(_.split, /\s+/)
gives a function that takes a string to split on /\s+/
.
I apologize for any excess verbosity.
The other part of this solution is _.flow
. Flow is basically lodash parlance for compose (though most implementations of compose tend to apply functions in the opposite order; from right to left). _.flow
takes an array of functions and returns a single function that applies each function in that array in order. For example, _.flow([add1, mult2])
would give you a function that adds one to a number, then multiplies it by two and returns the result.
In this context, flow
takes our custom operations that we created with partialRight
and applies them in order to the argument it gets. In this case, that means it gets a string, splits it on /\s+/
, maps to _.capitalize
, and joins on ' '
, in that order.
This might be over-engineered for your purposes but it was fun to put together nonetheless.