Converting Odd and Even-indexed characters in a string to uppercase/lowercase in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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 −

Example

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. The output in console will be −

Output

hElLo wOrLd, It iS So nIcE To bE AlIvE.
raja
Published on 19-Aug-2020 10:23:38
Advertisements