Convert each first letter of each word to uppercase

11

I have the following question:

  

Write a titleize (text) function that converts each first letter of each word to uppercase.

     

ex: titleize ("this IS just A tExT"); // correct output - > (This Is Just A Text.)

I was able to leave the first few letters of each word in capitals, but I have no idea how to change the rest of the letters to lowercase .

I found my solution verbose if they had something more elegant.

Follow the code so you can see what I'm doing:

function titleize(text) {

    // Convertendo primeira letra em maiuscula.
    text = text.charAt(0).toUpperCase() + text.slice(1);

    for (var i = 0; i < text.length; i++) {
        if (text.charAt(i) ===" ") {

            // Convertendo letra após o ESPAÇO em maiuscula
            var charToUper = text.charAt(i+1).toUpperCase();

            // Colocando texto de antes do ESPAÇO na variável
            var sliceBegin = text.slice(0, (i+1));

            // colocando o texto de depois do ESPAÇO na variável
            var sliceEnd = text.slice(i + 2);

            // Juntando tudo
            text = sliceBegin + charToUper + sliceEnd;

        } else {

            // NAO CONSIGO PENSAR EM COMO TRANSFORMAR O RESTANTE DAS LETRAS EM MINUSCULA
        }   
    }
    return text;
}
console.log (titleize("this IS just A tExT"));

Notice that I did nothing about the central letters of each word, so they return both uppercase and lowercase letters: /

My current output on the console:

How could I solve this problem?

    
asked by anonymous 10.09.2014 / 18:48

4 answers

14

What about something like:

function titleize(text) {
    var loweredText = text.toLowerCase();
    var words = loweredText.split(" ");
    for (var a = 0; a < words.length; a++) {
        var w = words[a];

        var firstLetter = w[0];
        w = firstLetter.toUpperCase() + w.slice(1);

        words[a] = w;
    }
    return words.join(" ");
}

Being very minimalistic, it can be written like this too:

function titleize(text) {
    var words = text.toLowerCase().split(" ");
    for (var a = 0; a < words.length; a++) {
        var w = words[a];
        words[a] = w[0].toUpperCase() + w.slice(1);
    }
    return words.join(" ");
}

The idea is to break the text into parts, and work each part separately. Breaking the text through the spaces, you do not have to worry about the specific treatment for that character.

If you want to include a hyphen or another character as a word separator, simply break the words inside the loop, or create a function to mount your array. Do not forget to handle the joining of the components later to put the phrase back as a string!

    
10.09.2014 / 19:37
12

An alternative:

var teste = "this IS just A tExT";
teste = teste.toLowerCase().replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });

console.log(teste);

Explanation:

First convert the whole word into lower case, then through a regular expression get the first letter and all the letters that follow a blank space, replacing it with the respective upper case.

The regular expression:

  • ?: - Makes the expression between parentheses not memorized
  • ^ - Match the first letter of the string
  • | - Operator "or"
  • \ s - Make a space
  • \ S - Matches a character other than white space.

You can read more about regular expressions at developer.mozilla.org >

    
13.09.2014 / 21:30
2

I made a small change in the code of the Colleague above, so he did not give toUpperCase() at all, type "Maria Da Silva E Melo", now stands Maria da Silva e Melo ....

function titleize(text) {
    var loweredText = text.toLowerCase();
    var words = loweredText.split(" ");
    for (var a = 0; a < words.length; a++) {
        var w = words[a];

        var firstLetter = w[0];
// aqui abaixo alterei 

        if( w.length > 2){ 
           w = firstLetter.toUpperCase() + w.slice(1);
        } else {
           w = firstLetter + w.slice(1);
        }

        words[a] = w;
    }
    return words.join(" ");
}

console.log (titleize("this IS just A tExT"));
    
04.07.2017 / 02:14
1
function titleCase(str) {
 //pega apenas as palavras e tira todos os espaços em branco.
 return str.replace(/\w\S*/g, function(str) {

  //passa o primeiro caractere para maiusculo, e adiciona o todo resto minusculo
  return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
 });
}

titleCase("testando a sTriNG");
    
02.04.2016 / 18:17