Search code examples
javascriptregextypescriptecmascript-6ecmascript-5

JS : How to capitalize first letter of each symbol-separated word in a string?


My JS woks well when the string has one word:

  • BRUNO ==> Bruno

It works well also when the string is a space sEparated words :

  • JEAN MARC ==> Jean Marc

But when it's an underscore separated words i got? :

  • JEAN-FRANCOIS ==> Jean-francois (wrong)

My purpose is to generalize it to get that :

  • JEAN-FRANCOIS ==> Jean-Francois

How do I make it become LIKE THAT?

My script is that :

capitalizeString(str) {
    var lowerString = str.toLowerCase();
    return lowerString.replace(/(^| )(\w)/g, (x) => {
      return x.toUpperCase();
    });
}

Solution

  • You can add the hyphen (-) as part of the RegEx:

    function capitalizeString(str) {
        var lowerString = str.toLowerCase();
        return lowerString.replace(/(^|[ -])(\w)/g, (x) => {
          return x.toUpperCase();
        });
    }
    
    console.log(capitalizeString('BRUNO'));
    console.log(capitalizeString('JEAN MARC'));
    console.log(capitalizeString('JEAN-FRANCOIS'));