-3

Apply the map() function to the variable str so that every second word in the string is converted to uppercase. in javascript.

str = "hello my name is jon and i live in. canada."
  • 4
    SO what did you attempt? – epascarello Jan 07 '22 at 16:03
  • https://stackoverflow.com/questions/18473326/javascript-break-sentence-by-words – epascarello Jan 07 '22 at 16:04
  • 1
    Use [`split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) to get the words, and then utilize the second parameter of [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) (*the index of the word*) to identify if it is an even word that needs capitalization. – Gabriele Petrioli Jan 07 '22 at 16:05

1 Answers1

1
"hello my name is jon and i live in. canada."
    .split(" ")
    .map((word, idx) => idx % 2 === 0 ? word : word.toUpperCase())
    .join(" ")

The trick is:

  1. Split by spaces.
  2. Map with index, but only use toUpperCase() if idx % 2 !== 0.
  3. Then join back with spaces.
Jaacko Torus
  • 796
  • 7
  • 24