How to select random two consecutive digits from a number in JavaScript

1 Answer

0 votes
function getRandomTwoDigits(num) {
  const s = String(num);

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

  const start = Math.floor(Math.random() * (s.length - 1)); 

  return s.slice(start, start + 2);
}

function main() {
  const num = 123456;
  const randomTwo = getRandomTwoDigits(num);

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

main();

  
  
/*
run:
            
Random two digits: 12
      
*/

 



answered Nov 26, 2025 by avibootz
edited Nov 26, 2025 by avibootz
...