[Solved-6 Solutions]Generate random string/characters in JavaScript - javascript tutorial



Problem:

How to generate random string/characters in JavaScript ?

Solution 1:

  • To create a random sequence of numbers and/or text. The function which generates the random string can be called from any event handler.

Step 1

  • Add the following code to your head
<script language="javascript" type="text/javascript">
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;
}
</script>

To set the variables,

  • chars
    • The random string will be created from these characters.
  • string_length
    • The length of the random string.

Step 2

  • Use the following code for your text field and button
<form name="randform">
<input type="button" value="Create Random String" onClick="randomString();"> 
<input type="text" name="randomfield" value="">
</form>

Solution 2:

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

console.log(makeid());

Solution 3:

let r = Math.random().toString(36).substring(7);
console.log("random", r);

Solution 4:

Method 1

If we're able to do this server-side, just use the crypto module

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes which means 40 characters of hex.

Method 2

If we have to do this client-side, perhaps try the uuid module

var uuid = require("uuid");
var id = uuid.v4();

// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"

Method 3

If we have to do this client-side and we don't have to support old browsers, we can do it without dependencies

// dec2hex :: Integer -> String
function dec2hex (dec) {
  return ('0' + dec.toString(16)).substr(-2)
}

// generateId :: Integer -> String
function generateId (len) {
  var arr = new Uint8Array((len || 40) / 2)
  window.crypto.getRandomValues(arr)
  return Array.from(arr, dec2hex).join('')
}

console.log(generateId())
// "82defcf324571e70b0521d79cce2bf3fffccd69"

console.log(generateId(20))
// "c1a050a4cd1556948d41"

Solution 5:

A small probability producing short strings or even an empty string (if the random number is 0), which may break your application. Here is a solution:

(Math.random().toString(36)+'00000000000000000').slice(2, N+2)

Second, both the original and the solution above limit the string size N to 16 characters. The following will return a string of size N for any N (but note that using N > 16 will not increase the randomness or decrease the probability of collisions):

Array(N+1).join((Math.random().toString(36)+'00000000000000000').slice(2, 18)).slice(0, N)

Explanation:

  • Pick a Random number in the range [0,1], i.e. between 0 (inclusive) and 1 (exclusive).
  • Convert the number to a base-36 string, i.e. using characters 0-9 and a-z.
  • Pad with zeros (solves the first issue).
  • Slice off the leading zeros, i.e. prefix and extra padding zeros.
  • Repeat the string enough times to have at least N number of characters in it (by Joining empty strings with the shortest random string used as the delimiter).
  • Slice exactly N characters from the string.

Solution 6:

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}


Related Searches to javascript tutorial - Generate random string/characters in JavaScript