How to select random two digits from anywhere in a number with JavaScript

1 Answer

0 votes
// Function to select random two distinct digits from a number
function getRandomTwoDigits(number) {
  const numStr = String(number);

  if (numStr.length < 2) {
    return "Error: number must have at least 2 digits";
  }

  // Generate two distinct random indices
  const i = Math.floor(Math.random() * numStr.length);
  let j;
  do {
    j = Math.floor(Math.random() * numStr.length);
  } while (j === i); // ensure different positions

  // Form the two-digit string
  return numStr[i] + numStr[j];
}

// Main
const num = 1234567;
const randomTwo = getRandomTwoDigits(num);

console.log("Random two digits:", randomTwo);

  
  
/*
run:
            
Random two digits: 15
      
*/

 



answered Nov 26, 2025 by avibootz
...