How to join strings in a for loop in Javascript?

Viewed 606

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')
10 Answers

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

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.

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.

finalResult is a String, not an Array so there is no join function.

Use this instead :

function generateHashtag (str) {

 let arrayWords = str.split(' ')
 const titleCasedArray = arrayWords.map(word => titleCaseWord(word))
 return titleCasedArray.join('');

}

function titleCaseWord (word){
  return word.slice(0,1).toUpperCase() + word.slice(1,-1).toLowerCase()

}



You can do something like this:

function generateHashtag (str) {
  //returns array of strings
  let split = str.split(' ') 
  //returns array of strings with each word capitalized
  const capitalizedWordsArr = split.map( word => word.charAt(0).toUpperCase() + word.substring(1))
  //returns a string by joining above array with no spaces
  return capitalizedWordsArr.join('') 
}

Javascript strings are immutable so you cannot overwrite them on the go, but you can overwrite array elements.

By using String.prototype.substr() you can extract a part of the string, you can use these parts, modify it and create a new string then replace the old array element. finally returning the joined string like you wanted to

function generateHashtag(str) {

    const split = str.split(' ') // array of words

    for (let i = 0; i < split.length; i++)
        split[i] = split[i].substr(0, 1).toUpperCase() + split[i].substr(1); // overwriting existing elements with Titlecased words

    return split.join('');  // returning final string

}

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

This is a perfect use-case for Array.prototype.reduce:

function generateHashtag(str) {
  return str
    .split(' ')
    .reduce((acc, [firstLetter, ...rest]) => acc += `${firstLetter.toUpperCase()}${rest.join('')}`,
    ''
  );
}
console.log(generateHashtag('Hello my name is')); // should return ('HelloMyNameIs')

If you want something similar to your code, but working, i would do this:

function generateHashtag (str) {
  let split = str.split(' ')
  let newStr = []

  for (let i = 0; i < split.length; i++){
    newStr.push(split[i].charAt(0).toUpperCase() + split[i].substring(1))
  }

  return newStr.join('')
}

You could also choose to do this task using a 'regular expression'. https://cheatography.com/davechild/cheat-sheets/regular-expressions/

Here is a quick implementation:

const generateHashtag = str => {
  // regular expression to capitalize the words
  const regEx = /(\b[a-z](?!\s))/g
  str = str.replace(regEx, (char) => {
    return char.toUpperCase()
  });

  // remove spaces, return
  return str.split(' ').join('')
}

Same code, but with less readability:

const generateHashtag = str => {
  return str.replace(/(\b[a-z](?!\s))/g, (char) => {
    return char.toUpperCase()
  }).split(' ').join('');
}

function generateHashtag (str) {
    return str.replace(/\b\S/g, e => e.toUpperCase()).replace(/\s/g,'');
}

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

\b: bondary \S: non space \s: space. https://regex101.com/

//try this code solve your problem 

const generateHashtag = str => {
    let split = str.split(' ')
    let finalResult = []
    for (word of split) {
        finalResult.push(word[0].toUpperCase() + word.substring(1))
    }
    return finalResult.join('')
}

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

Related