Convert every first letter of every word into uppercase

Asked

Viewed 34,672 times

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:

saida do 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?

  • Let’s consider the score, I think we get a more complete solution.

  • 4

    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.

  • It worked @bfavaretto. Ok anyway your solution solves my current problem :) thank you very much.

8 answers

19


How 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 minimalist, it can be written as well:

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 by spaces, you don’t have to worry about the specific treatment for this character.

If you want to include a hyphen or other character as a word separator, simply break the words inside the loop, or create a function to mount your array. Don’t forget to treat component merge later to reassemble the phrase as a string!

  • 2

    Renan thank you very much, really you simplified things. D

17

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 to 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 uppercase letter.

The regular expression:

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

You can read more about regular expressions in Developer.mozilla.org

  • Tip: it’s nice to explain why your code solves the problem. PS: I wrote this comment in the analysis queue of Low quality publications, because code-only answers are automatically put there for analysis.

  • 1

    Since I already had an answer pointed out to be correct, I thought there would be no need to go into great detail. But I’ve already added a brief explanation. Thank you.

  • 3

    Show, super complete! Even if it’s brief, an explanation is the difference between "ok" and "OOOOK":) . . . . . . Of interest, a recent discussion at Meta: Teach to fish, or give the fish?

  • +1 for using regular expressions!

3

Another alternative, based on the famous map:

function titleize(string, separator = ' ') {
  return string
    .split(separator)
    .map((word) => word[0].toUpperCase() + word.slice(1).toLowerCase())
    .join(separator);
}

console.log(titleize('OLÁ como vAI?'));
console.log(titleize('hELLO wORLD!'));

The operation is simple:

A function is created that takes two arguments - the string to be formatted and a separator, which by default is a blank space. With this:

  • Separate the received string with the separator;
  • Iterate over each word (through the method Array.prototype.map), capitalizing on the first letter and turning the rest into lowercase;
  • Merge all formatted words using the tab.

3

I made a small change in the code of the Colleague above, so that it does not give toUpperCase() in everything, like "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"));
  • How would you use this function directly in an input?

2

In this solution it is good for proper names to avoid that prepositions become uppercase.

function processString(text) {
        let loweredText = text.toLowerCase();
        let wordsArray = loweredText.split(" ");

        let words = wordsArray.map((word)=> {
            let firstLetter = word[0];
            if( word.length > 2){
                return firstLetter.toUpperCase() + word.slice(1);
            } else {
                return firstLetter + word.slice(1);
            }
        });
        return words.join(" ");
    }
    processString('fuLanO De tAL');

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");

0

I did so:

var titleize = (word) => {
  var newWord = [];
  var splited = word.split(" ");

  splited.forEach( word => {
    var firstLetter = word[0].toUpperCase();
    var restLetters = word.slice(1).toLowerCase();
    newWord.push(firstLetter+restLetters) 
  })

  return newWord.join(" ");
}

console.log(titleize("this IS just A tExT"));

I turned the string into an array with the method split and then I worked on each item of the array. It’s not as pretty when using regular expression, but it’s worth.

0

From to use a function this way with Javascript

function capitalize(str) {
  if (typeof str !== 'string') {
    return '';
  }

  return `${str.charAt(0).toUpperCase()}${str.substring(1).toLowerCase()}`;
}

or with Typescript

  export function capitalize(str: string) {
  if (typeof str !== 'string') {
    return '';
  }

  return `${str.charAt(0).toUpperCase()}${str.substring(1).toLowerCase()}`;
}

Browser other questions tagged

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