简体   繁体   中英

How to format strings with special characters like '&' in Lodash?

I'm using Lodash to format a string like DIGITAL & TECHNOLOGY into Digital & Technology . I've tried with the following code:

_.startCase(_.lowerCase('DIGITAL & TECHNOLOGY'));

However, this returns me Digital Technology .

This didn't work either:

var words = _.words('DIGITAL & TECHNOLOGY', /[^ ]+/g);
var newWords = '';
_.forEach(words, function(w){
  newWords += _.capitalize(w);
})

This returns Digital & technology .

What would be an appropriate way to properly format strings like these using Lodash only? Or must I use a mix of Lodash and Javascript?

Replace each sequence of word characters, with a capitalized version:

 var str = 'DIGITAL & TECHNOLOGY'; var result = str.replace(/\\w+/g, _.capitalize); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

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 (ie 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 (ie 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.

You can use _.capitalize to capitalize the first character, and then use regular expression to replace all other first letters of words:

 var result = _.capitalize('DIGITAL & TECHNOLOGY').replace(/\\s(\\S)/g, function(v) { return v.toUpperCase(); }); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

Lodash has another method, toLower, that takes the string as a whole and not as space separated words like lowerCase.

https://lodash.com/docs/4.17.4#toLower

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM