-3

I am able to create single alphanumeric string at a time by clicking on a button by using Math.random() function.

But i need to print 5 alphanumeric random values at a time by clicking on button. Please help me out I am beginner in javascript and got stuck. I really need some solution for that

2 Answers2

0

This works by generating random numbers in base 10 then converting them to base 36, where digits include both numbers and letters (10 digits + 26 letters = 36).

'use strict';
document.querySelector('button').onclick = function () {
  const strings = new Array(5)
    .fill()
    .map(() => Math.random() * 10000)
    .map((n) => n.toString(36).replace(/\./, ''));
  console.log(strings);
}
<button>Click</button>
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
0

This works: Generating random number with Math.random between 65 and 100 (ASCII: A-Z and 10 more for the digits) and useString.fromCharCode to convert it to char. For getting the number subtratct the differnce in ASCII if the random is greater 90. Use a for-loop and add the chars.

document.getElementById('btn').addEventListener('click', () => {
    let random = '';
    for (let x = 0; x < 5; x++) {
        let randInt = Math.floor((Math.random() * 35) + 65);
        random += String.fromCharCode((randInt<=90) ? randInt : randInt-43);
    }
    document.getElementById('random').textContent=random;
});
<button id='btn'>Random</button>
<div id='random'></div>
Sascha
  • 4,576
  • 3
  • 13
  • 34