Skip to main content
acnatlhi
New Participant
September 26, 2017
Question

Generate random string via Javascript

  • September 26, 2017
  • 3 replies
  • 3374 views

Hello all!

I am not good with Javascript but was able to come up with random numbers using these forums and Google.

Does anyone know how to come up with a random string?  IE 6 to 8 characters of numbers and letters?  I have seen some Javascript that seems to work but not sure if getting it to work in Captivate is different as I have not had success.

This is what I used for number:

function getRandomInt(min, max) {

   var jsRandomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

   alert(jsRandomNumber);

}

getRandomInt(0,1000);

Appreciate the time!

    This topic has been closed for replies.

    3 replies

    New Participant
    October 15, 2022

    We can simply use short JS code as below for 6 characters string

    let random = (Math.random() + 1).toString(36).substring(6);
    console.log(random);

    You can take a look at more ways here:

    https://qawithexperts.com/questions/242/how-to-generate-random-string-using-javascript

    Thanks.

    New Participant
    May 9, 2018

    Hello!

    You should use, for example:

    function getRandomString(l) {   

        var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        var charsLength = chars.length;

        var string = '';

         for(var i=0; i<l; i++) {

            string += chars.charAt(Math.floor(Math.random() * charsLength));

        }

       return string;

    }

    more variants how to generate random string in js: http://javascript-benchmark.info/t/generate-random-string

    New Participant
    December 16, 2017

    You could try this:

    function randomString() {

    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

    var string_length = 8;

    var randomstring = '';

    for (var i=0; i<string_length; i++) {

    var rnum = Math.floor(Math.random() * chars.length);

    randomstring += chars.substring(rnum,rnum+1);

    }

    document.randform.randomfield.value = randomstring;

    }

    Then you can put in a form with "onkeyup="randomString();"" or a button with "onclick="randomString();"".