0

I am trying to generate a random string of 5 OR 7 alphanumeric characters (Upper or lowercase)

Currently, I have:

var randStr = randomString(5);

but I am too novice to know how to make it generate either 5 or 7 characters in the string. I need it to randomly choose a 5 or 7 character string to generate.

I used

 function randomString(string_length) {
                var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
                var output = "";
                var index;

                for (var i = 0; i < string_length; i++) {
                    var index = Math.floor(Math.random() * chars.length);
                    output += chars.substring(index, index + 1);
                }
                document.getElementById("current").innerHTML = output;
                return output;

and

var randStr = randomString(5);

to get an output of a 5 character alphanumeric string but I need a 5 or a 7 randomly instead of switching it from a 5 to a 7. I want an either or.

FoxOrd
  • 1
  • 1
  • Can’t you just do a “coin flip” to decide whether to provide 5 or 7 as an argument? `randomString(Math.random() < 0.5 ? 5 : 7)`. – Terry Mar 08 '23 at 06:20
  • I tried to flat out replace the randStr = randomString(5) with that and it did not work. I am really in over my head with this as I am not good with coding, what am I doing wrong here? – FoxOrd Mar 08 '23 at 09:27

3 Answers3

0

it's my code ,u can specify the length of the characters

let randomeName = (length: number = 8): string => {
  let alphabet = [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
  ];
  let arr: string[] = [];
  for (let i = 0; i <= length; i++) {
    let idx: number = +(Math.random() * 51).toFixed(0);
    arr.push(alphabet[idx]);
  }
  return arr.join('');
};
0
let r;
if(Math.random() < 0.5){
r = (Math.random() + 1).toString(36).substring(7);
console.log("random 5:", r);
} else {
r = (Math.random() + 1).toString(36).substring(5);
console.log("random 7:", r);
}
user1844933
  • 3,296
  • 2
  • 25
  • 42
0

Based on this great answer:

function randomString() {
  const length = (Math.random() < 0.5) ? 5 : 7;
  return (Math.random() + 1).toString(36).substring(length);
}

console.log(randomString())
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34