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.

Understanding the Pattern

A zig-zag pattern alternates between lowercase and uppercase characters based on their index position. Even indices (0, 2, 4...) become lowercase, while odd indices (1, 3, 5...) become uppercase.

Example Implementation

const text = 'Hello world, it is so nice to be alive.';

const changeCase = (str) => {
    const newStr = str
        .split("")
        .map((char, index) => {
            if(index % 2 === 0){
                return char.toLowerCase();
            } else {
                return char.toUpperCase();
            }
        })
        .join("");
    return newStr;
};

console.log(changeCase(text));
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.

Simplified Version

const zigZagPattern = (str) => {
    return str
        .split("")
        .map((char, index) => 
            index % 2 === 0 ? char.toLowerCase() : char.toUpperCase()
        )
        .join("");
};

console.log(zigZagPattern("JavaScript"));
console.log(zigZagPattern("Programming"));
jAvAsCrIpT
pRoGrAmMiNg

Visual Pattern

Zig-Zag Pattern Example Original: HELLO 0 1 2 3 4 Result: h E l L o Even index = lowercase Odd index = uppercase

Alternative Approach Using For Loop

function zigZagLoop(str) {
    let result = "";
    for (let i = 0; i 

tUtOrIaL

Conclusion

The zig-zag pattern creates alternating uppercase and lowercase characters based on index position. Use the map() method for functional programming style or a simple for loop for better performance with large strings.

Updated on: 2026-03-15T23:19:00+05:30

703 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements