skip to Main Content
function generateHashtag(str) {
  const words = str.split(" ");
  for (let i = 0; i < words.length; i++) {
    words[i] = words[i][0].toUpperCase() + words[i].substr(1);
  }
  words.join(" ");

  return words
}
console.log(generateHashtag("i am a good coder"))

This is the code I have come up with but after iterating the string, the output is an array with the first words capitalized. How do I join up the words from the array to form back the sentence without the spaces?

2

Answers


  1. Array#join() returns a new string. Return that value directly instead of calling it on words without assignment.

    function generateHashtag(str) {
      const words = str.split(" ");
      for (let i = 0; i < words.length; i++) {
        words[i] = words[i][0].toUpperCase() + words[i].substr(1);
      }
    
      return words.join(" ");
    }
    
    console.log(generateHashtag("i am a good coder"));

    From developer.mozilla.org

    The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

    Login or Signup to reply.
  2. words.join() creates a new value, it doesn’t update the words value.

    Try this:

    function generateHashtag(str) {
      const words = str.split(" ");
      for (let i = 0; i < words.length; i++) {
        words[i] = words[i][0].toUpperCase() + words[i].substr(1);
      }
    
      return words.join(' ')
    }
    console.log(generateHashtag("i am a good coder"))
    

    Here we return words.join(‘ ‘)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search