How to define Titlecase using regex in Javascript?

Asked

Viewed 100 times

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 is ignoring it:

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

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

It doesn’t matter if you break the teste2.

1 answer

9


Just replace g2.toLowerCase() by just g2, so that there is no passage into the lower case characters of those in 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 said yourself, teste2 will no longer stick with the lowercase middle characters, thus getting broken.

jsfiddle of example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.