2

I want to generate random a - z letter(1 letter) in JavaScript without typing all letters. But I don't know how. I want to use Math.floor(Math.random * ?). But I don't know what is ?. I want to use JavaScript in this HTML code:

<!DOCTYPE html>
<html>
  <head>
    <title>AZ Generator</title>
  </head>
  <body>
    <script src="az-generator.js"></script>
    <button onclick="az()">Generate</button>
    <p id="p"></p>
  </body>
</html>
Arian
  • 63
  • 1
  • 7

2 Answers2

5

There're 2 things you need:

  • Something to bridge the gap between numbers and characters and that could be String.fromCharCode()
  • Random number within a proper range to get one of required characters (for lower case letters that would be the range of 26 ASCII chars starting from char code 97)

So, the solution could be as simple as that:

const randomLetter = _ => String.fromCharCode(0|Math.random()*26+97)

console.log(randomLetter())

If you need to extend that to get random string of desired length (say, 15 chars long), you may go like that:

const randomLetter = _ => String.fromCharCode(0|Math.random()*26+97),

      randomStrOf15Chars = Array(15).fill().map(randomLetter).join('')
      
console.log(randomStrOf15Chars)      
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
0

You could create a random number of 0 ... 25 and add 10 and convert the number to string with a base of 36.

function az() {
   return Math.floor(Math.random() * 25 + 10).toString(36);
}

console.log(Array.from({ length: 50 }, az).join(''));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392