Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda