Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
How to join strings in a for loop in Javascript?

I am trying to capitalise the first character of each word and join all words into one string. I have managed to capitalise the first character of each word but cant seem to get .join() to work on the final result

function generateHashtag (str) {

 let split = str.split(' ')

 for(let i = 0; i < split.length; i++){

  let finalResult = split[i].charAt(0).toUpperCase() + split[i].substring(1)

   console.log(finalResult.join(''))

  }


}

console.log(generateHashtag('Hello my name is')) should return ('HelloMyNameIs')
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Achieving this by split is possible. first create an array of divided strings (by the delimiter ' ') and then loop around the array and capitalize the first char using the method toUpperCase and concat the rest of the string without the first letter using slice

function generateHashtag(str) {
  let split = str.split(' ');
  for (let i = 0; i < split.length; i++) {
    split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
  }
  return split.join('');
}

console.log(generateHashtag('Hello my name is'));

More about split - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

about 4 years ago · Juan Pablo Isaza Relatório

0

you can do split[i] = split[i].charAt(0).toUpperCase() + split[i].substring(1) in the loop then outside loop do split.join('')

Basically you are replacing each word (split[i]) with capitalised word. Then in the end join the words.

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need to use join at all, just declare and initialize finalResult outside the loop and concatenate each word inside the loop:

function generateHashtag(str) {

    const split = str.split(' '); // Array<String>
    let finalResult = ''; // String

    for(let i = 0; i < split.length; i++) {

        const titleCased = split[i].charAt(0).toUpperCase() + split[i].substring(1);
        finalResult += titleCased;
    }

    return finalResult;
}

console.log(generateHashtag('Hello my name is'));
  • However, you can simplify this code considerably by using a functional-programming (FP) style with map and reduce. See below.
  • I've also changed your code to use toLocaleUpperCase instead of toUpperCase and uses [0] for brevity.
  • It's still safe to use substring(1) for single-character strings, it just returns ''.
function generateHashtag(str) {
    return ( str
        .split(' ')
        .map( word => word[0].toLocaleUpperCase() + word.substring(1).toLocaleLowerCase() )
        .reduce( ( word, concat ) => concat + word, "" )
    );
}

  • I forgot that join() can still be used instead of reduce (and will have an optimized implementation inside the JS engine anyway):
  • I've also moved the map function's logic to a named function toTitleCase.
function generateHashtag(str) {
    
    const toTitleCase( word ) => word[0].toLocaleUpperCase() + word.substring(1).toLocaleLowerCase();

    return ( str
        .split(' ')
        .map( word => toTitleCase( word ) ) // or just `.map( toTitleCase )`
        .join()
    );
}

The return statement has parens to prevent unwanted automatic-semicolon-insertion which would otherwise break the function.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda