skip to Main Content

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.

3

Answers


  1. 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('');
    };
    
    Login or Signup to reply.
  2. 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);
    }
    
    Login or Signup to reply.
  3. 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())
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search