Zig-Zag pattern in strings in JavaScript?

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

We need to write a function that reads a string and converts the odd indexed characters in the string to upperCase and the even ones to lowerCase and returns a new string.

Full code for doing the same will be −

const text = 'Hello world, it is so nice to be alive.';
const changeCase = (str) => {
   const newStr = str
   .split("")
   .map((word, index) => {
      if(index % 2 === 0){
         return word.toLowerCase();
      }else{
         return word.toUpperCase();
      }
   })
   .join("");
   return newStr;
};
console.log(changeCase(text));

The code converts the string into an array, maps through each of its word and converts them to uppercase or lowercase based on their index.

Lastly, it converts the array back into a string and returns it.

Following is the output on console −

hElLo wOrLd, It iS So nIcE To bE AlIvE.
raja
Updated on 09-Oct-2020 12:05:07

Advertisements