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

1 Answer

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

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

const str = "d2c54be3a1";
const output = moveDigitsToFront(str);

console.log(output); 

  
  
/*
run:
  
25431dcbea
  
*/

 



answered May 27, 2025 by avibootz
...