Search code examples
javascriptstringcase-sensitiveuppercaseletter

How to move all capital letters to the beginning of the string?


I've been practicing simple solutions using what I've been learning / known. The question I've faced is, how to move the capital letters in the string to the front?

I've solved it, but it's not to my expectation as my original idea was to → find the uppercase letter → put them in an array → concat the uppercase with the original string array with the uppercase letter removed in it.

Hence my question is, how can I remove the capital letter in the first conditional statement so I won't need to create another conditional statement to find the lower case and store the lower case letter in an array?

For example, the input string is 'heLLo' → output would be 'LLheo' (the capital letters are now in front).

Thank you!

function capToFront(s) {
    var sp = s.split("");
    var caps = []; 
    var lower = []
    for (var i = 0; i < sp.length; i++)
        {
            if (sp[i] == sp[i].toUpperCase()){              
                caps.push(sp[i]);
           **//How can i remove the capital letter in "sp" array as I've pushed them into the caps Array**

            }
            if (sp[i] == sp[i].toLowerCase()){
                lower.push(sp[i]);
            }
        }
    return caps.join("").concat(lower.join(""));
}

Solution

  • With RegExp, you can accomplish your goal in one line without any loops:

    const result = [...'heLLo'].sort(l => /[A-Z]/.test(l) ? -1 : 0).join('');
    
    console.log(result); // LLheo

    If you want to ensure the original order among the capital letters is preserved, it will be slightly longer:

    const result = [...'Hello World Foo Bar']
      .sort((a, b) => /[A-Z]/.test(a) ? /[A-Z]/.test(b) ? 0 : -1 : 0)
      .join('');
    
    console.log(result); // HWFBello orld oo ar