- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Zig-Zag pattern in strings 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 −
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.
Advertisements
To Continue Learning Please Login
Login with Google