
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Odd and Even Indexed Characters to Uppercase and Lowercase in JavaScript
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.
Advertisements