Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

target ever second word in a string using map function

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."

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading