17
I have the following question:
Write a titleize(text) function that converts every first letter of every word into uppercase.
ex: titleize("this IS just A Text"); // correct output -> (This Is Just A Text.)
I was able to capitalize the first letters of each word only that I have no idea how to get change the rest of the letters to lower case.
I found a little verbose my solution if you have something more elegant please feel free.
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"));
Note that I have done nothing in relation to the central letters of each word, so they return both upper and lower case :/
My current output on the console:
How could I solve this problem ?
"Word" is just what is separated by spaces or is it more complex? I mean, need to consider punctuation?
– bfavaretto
Let’s consider the score, I think we get a more complete solution.
– David Bastos
Okay, I can think about that later. But if the immediate problem is just to convert the rest to a minor, just apply a
toLowerCase()
in everything before hitting the first letters.– bfavaretto
It worked @bfavaretto. Ok anyway your solution solves my current problem :) thank you very much.
– David Bastos