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

We are required to write a JavaScript function that takes in a string with uppercase and lowercase letters. The function should return a string with all the uppercase letters moved to front of the string.

For example: If the input string is −

const str = 'heLLO woRlD';

Then the output should be −

const output = 'LLORDhe wol';


Following is the code −

const str = 'heLLO woRlD';
const moveCapitalToFront = (str = '') => {
   let capitalIndex = 0;
   const newStrArr = [];
   for(let i = 0; i < str.length; i++){
      if(str[i] !== str[i].toLowerCase()){
         newStrArr.splice(capitalIndex, 0, str[i]);
   return newStrArr.join('');


Following is the output in the console −

LLORDhe wol