Move string capital letters to front maintaining the relative order - JavaScript

We need to write a JavaScript function that takes a string with uppercase and lowercase letters and returns a new string with all uppercase letters moved to the front while maintaining their relative order.

For example, if the input string is:

const str = 'heLLO woRlD';

Then the output should be:

const output = 'LLORDhe wol';

Algorithm Explanation

The approach uses an array and a tracking index. We iterate through each character, and if it's uppercase, we insert it at the current capital position and increment the index. Lowercase characters are simply pushed to the end.

Implementation

const str = 'heLLO woRlD';

const moveCapitalToFront = (str = '') => {
    let capitalIndex = 0;
    const newStrArr = [];
    
    for(let i = 0; i 

LLORDhe wol

Alternative Approach Using Filter

Here's a cleaner approach using array filter methods:

const moveCapitalToFrontAlt = (str = '') => {
    const chars = str.split('');
    const uppercase = chars.filter(char => char !== char.toLowerCase());
    const lowercase = chars.filter(char => char === char.toLowerCase());
    
    return uppercase.concat(lowercase).join('');
};

console.log(moveCapitalToFrontAlt('heLLO woRlD'));
console.log(moveCapitalToFrontAlt('JavaScript'));
console.log(moveCapitalToFrontAlt('hello WORLD'));
LLORDhe wol
JSjavacript
WORLDhello 

How It Works

The first method maintains a capitalIndex that tracks where to insert the next uppercase letter. Each uppercase character gets inserted at this position, pushing previous lowercase characters further back. The second method separates uppercase and lowercase characters into different arrays, then concatenates them.

Comparison

Method Time Complexity Space Complexity Readability
Splice Method O(n²) O(n) Medium
Filter Method O(n) O(n) High

Conclusion

Both methods successfully move uppercase letters to the front while preserving relative order. The filter approach is more efficient and readable, while the splice method demonstrates array manipulation techniques.

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

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements