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>
                There're 2 things you need:
String.fromCharCode()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)
const randomLineOfLetters = (lineSize) => () => Array(lineSize)
  .fill()
  .map(randomLetter)
  .join('')
const randomLineOf15Letters = randomLineOfLetters(15)
      
console.log(randomLineOf15Letters())
Since you haven't mentioned case sensitivity, you may pick the starting char code from either [a-z] or [A-Z] ranges, or randomly apply .toUpperCase():
const randomLetterRandomCase = () => {
  const aCharCode = 97
  const capitalACharCode = 65
  const alphabetSize = 26
  const startChar = Math.random() < 0.5
    ? capitalACharCode
    : aCharCode
    
  return String
    .fromCharCode(0|Math.random()*alphabetSize+startChar)
}
const randomlyCasedRandomLetter = () => {
  const aCharCode = 97
  const alphabetSize = 26
  const isUpperCase = Math.random() < 0.5
  const randomLetter = String
    .fromCharCode(0|Math.random()*alphabetSize+aCharCode)
    
  return isUpperCase
    ? randomLetter.toUpperCase()
    : randomLetter
}
const randomLineOfLetters = (lineSize, letterPicker) => Array(lineSize)
  .fill()
  .map(letterPicker)
  .join('')
 
 
      
console.log(randomLineOfLetters(15, randomLetterRandomCase))
console.log(randomLineOfLetters(15, randomLetterRandomCase))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With