How to set TitleCase using regex in Javascript?

12

I have this function:

 var titleCase = function(s) {
         return s.replace(/(\w)(\w*)/g, function(g0, g1, g2) {
              return g1.toUpperCase() + g2.toLowerCase();
         });
    }

If I call her by passing something she works right:

var teste = titleCase("apenas um teste"), //"Apenas Um Teste"
    teste2 = titleCase("oUTRO.tesTE");     //"Outro.Teste"

But when I have an upperChar in the middle of the text, it should keep it, but instead it is ignoring it:

var teste3 = titleCase('testeControl'); //"Testecontrol"

Any suggestions for me to have teste3 result "TesteControl" ?

It does not matter if you break teste2 .

    
asked by anonymous 28.04.2014 / 19:45

1 answer

9

Just replace g2.toLowerCase() with just g2 , so you do not have to switch to lower-case characters from the middle of the word:

var titleCase = function(s) {
         return s.replace(/(\w)(\w*)/g, function(g0, g1, g2) {
              return g1.toUpperCase() + g2;
         });
    }

But as you have already said, teste2 will no longer be left with the middle characters in the middle, so it will be broken.

example jsfiddle

    
28.04.2014 / 19:51