-1

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?

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

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.

Behemoth
  • 5,389
  • 4
  • 16
  • 40
1

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(' ')