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.

Understanding Index-Based Case Conversion

In JavaScript, string indices start at 0. Even indices (0, 2, 4...) will be converted to lowercase, while odd indices (1, 3, 5...) will be converted to uppercase.

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));

Output

hElLo wOrLd, It iS So nIcE To bE AlIvE.

How It Works

The code converts the string into an array using split(""), maps through each character and converts them to uppercase or lowercase based on their index using the modulo operator (%). Finally, it converts the array back into a string using join("") and returns it.

Alternative Approach Using For Loop

const alternativeCaseConversion = (str) => {
    let result = '';
    for (let i = 0; i 

jAvAsCrIpT

Comparison

Method Readability Performance Memory Usage
Array methods (map/split/join) High Moderate Higher (creates intermediate arrays)
For loop with string concatenation Good Better Lower

Conclusion

Both approaches effectively convert characters based on their index position. The array method is more functional and readable, while the for loop approach is more performant for large strings.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements