Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random a - z letter(1 letter) in JavaScript without typing all letters? [duplicate]

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>
like image 270
Arian Avatar asked Nov 01 '25 09:11

Arian


1 Answers

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)

const randomLineOfLetters = (lineSize) => () => Array(lineSize)
  .fill()
  .map(randomLetter)
  .join('')

const randomLineOf15Letters = randomLineOfLetters(15)
      
console.log(randomLineOf15Letters())

Bonus:

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))
like image 162
Yevgen Gorbunkov Avatar answered Nov 02 '25 23:11

Yevgen Gorbunkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!