How to move the digits of a string with digits and letters to the beginning of the string in TypeScript

1 Answer

0 votes
function moveDigitsToFront(str: string): string {
    // Separate digits and non-digits using regex
    const digits: string = str.replace(/\D/g, ""); // Extract digits
    const nonDigits: string = str.replace(/\d/g, ""); // Extract non-digits

    // Combine digits and non-digits
    return digits + nonDigits;
}

const str = "d3c54be2a1";
const output: string = moveDigitsToFront(str);

console.log(output); 

  
  
/*
run:
  
"35421dcbea" 
  
*/

 



answered May 27, 2025 by avibootz
...