Search code examples
javascriptdictionarylodashcapitalize

lodash capitalize wont capitalize anything other then the first entry


consider the following code:

lawCannotUse = lawCannotUse.map(function(cannotUse){
  console.log(cannotUse, lodashCapitalize(cannotUse));
  upperCaseCannotUse.push(lodashCapitalize(cannotUse));
});

lawCannotUse is an array of strings.

The console.log shows:

enter image description here

As you can see, the first on is capitalized, but nothing else is, attack should be and so should spark.

What is: lodashCapitalize ?

var lodashCapitalize  = require('../../../node_modules/lodash/string/capitalize');

Any ideas?


Solution

  • It appears that all strings in your array after the first one have a leading space. _.capitalize makes no effort to trim the string or to uppercase the first alphanumeric character. You can, however, trim the strings manually using _.trim:

    var _ = require('lodash');
    
    lawCannotUse = lawCannotUse.map(function (cannotUse) {
      console.log(cannotUse, _.capitalize(_.trim(cannotUse)));
      // ...
    });
    

    You can also compose the two functions to produce a reusable function like so

    var myCapitalize = _.compose(_.capitalize, _.trim);
    // ...
    myCapitalize("   abc");  // gives "Abc"