
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Converting Odd and Even-indexed characters in a string to uppercase/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.
- Related Questions & Answers
- Converting strings to uppercase and lowercase with vanilla JavaScript
- Replacing upperCase and LowerCase in a string - JavaScript
- JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference
- How to get odd and even position characters from a string?
- Java program to convert a string to lowercase and uppercase.
- Java program to find the percentage of uppercase, lowercase, digits and special characters in a String
- Convert string to lowercase or uppercase in Arduino
- Check if lowercase and uppercase characters are in same order in Python
- Absolute Difference of even and odd indexed elements in an Array (C++)?
- Separate odd and even in JavaScript
- Absolute Difference of even and odd indexed elements in an Array in C++?
- Return element-wise a copy of the string with uppercase characters converted to lowercase and vice versa in Numpy
- How to test if a letter in a string is uppercase or lowercase using javascript?
- Golang Program to convert Uppercase to Lowercase characters, using binary operator.
- Making a Java String All Uppercase or All Lowercase.
Advertisements