How to get odd and even position characters from a string?

In JavaScript, you can extract characters from odd and even positions in a string using various methods. This technique is useful for string manipulation tasks like creating puzzles, encoding, or data processing.

Understanding the Problem

Given a string, we want to separate characters based on their position index:

  • Even positions (0, 2, 4...): "T", "i", " ", "s", " ", "a", " ", "e", "t", "!"
  • Odd positions (1, 3, 5...): "h", "s", "i", "", "i", "", "t", "s", ""
If the string is "This is a test!"
Even positions: "Ti s  a et!"
Odd positions: "hsi s ts"
Combined result: "hsi etTi sats!"

Using Array reduce() Method

const string = 'This is a test!';

const separateString = (str) => {
    const { odd, even } = [...str].reduce((acc, val, ind) => {
        const { odd, even } = acc;
        return {
            odd: ind % 2 === 1 ? odd + val : odd,
            even: ind % 2 === 0 ? even + val : even
        };
    }, {
        odd: '',
        even: ''
    });
    return odd + even;
};

console.log(separateString(string));
hsi etTi sats!

Using Simple Loop Method

function getOddEvenChars(str) {
    let oddChars = '';
    let evenChars = '';
    
    for (let i = 0; i < str.length; i++) {
        if (i % 2 === 0) {
            evenChars += str[i];
        } else {
            oddChars += str[i];
        }
    }
    
    return oddChars + evenChars;
}

const testString = 'Hello World';
console.log(getOddEvenChars(testString));
el olHlo Wrd

Using Array filter() Method

function separateByPosition(str) {
    const chars = str.split('');
    
    const oddPosition = chars.filter((char, index) => index % 2 === 1).join('');
    const evenPosition = chars.filter((char, index) => index % 2 === 0).join('');
    
    return oddPosition + evenPosition;
}

console.log(separateByPosition('JavaScript'));
aacitJvSrp

Comparison of Methods

Method Performance Readability Memory Usage
reduce() Good Complex Low
Simple Loop Best High Low
filter() Slower High Higher

Practical Use Case

// Creating a simple encoding function
function encodeString(str) {
    return getOddEvenChars(str);
}

function decodeString(encodedStr) {
    const mid = Math.ceil(encodedStr.length / 2);
    const oddChars = encodedStr.slice(0, mid);
    const evenChars = encodedStr.slice(mid);
    
    let result = '';
    for (let i = 0; i < Math.max(oddChars.length, evenChars.length); i++) {
        if (evenChars[i]) result += evenChars[i];
        if (oddChars[i]) result += oddChars[i];
    }
    return result;
}

const original = "Secret Message";
const encoded = encodeString(original);
const decoded = decodeString(encoded);

console.log("Original:", original);
console.log("Encoded:", encoded);
console.log("Decoded:", decoded);
Original: Secret Message
Encoded: ece esg Srt Mesa
Decoded: Secret Message

Conclusion

Extracting odd and even position characters is accomplished efficiently using loops, reduce(), or filter() methods. The simple loop approach offers the best performance, while functional methods like reduce() provide more concise solutions for complex string manipulations.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements