Search code examples
javascriptlodash

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?


Solution

  • 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>