How to generate random string using javascript?


Hi, I would like to generate the random string using javascript? How can I achieve it?

Any length of string would work but if possible I would like to have a random string of 6 characters.


Asked by:- Vinnu
1
: 5801 At:- 2/27/2018 12:32:48 PM
javascript random string generation







3 Answers
profileImage Answered by:- jaiprakash

There are multiple ways to generate random string in javascript:

1. Using Math.Random

Math.random().toString(36).substring(6); // .substring(6) for 6 characters

2. Creating a function

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;
}

You can call the above function like

<input type="button" value="Generate Random String" onClick="randomString();">

3. Using Crypto.getRandomValue()

This solution works on modern browsers only.

crypto.getRandomValues() method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers

Example

// convert 0-255 -> '00'-'ff'
function decimalToHex (dec) {
  return dec.toString(16).padStart(2, "0")
}

function generateId (len) {
  var arr = new Uint8Array((len || 40) / 2) // make array of 4 bytes (values 0-255)
  window.crypto.getRandomValues(arr)
  return Array.from(arr, decimalToHex).join('')
}
//call function
console.log(generateId(20))

Fiddle: https://jsfiddle.net/hcgym502/

Thanks

3
At:- 2/28/2018 7:23:21 AM Updated at:- 10/15/2022 6:52:27 AM
Looks good 0
By : neena - at :- 3/23/2018 7:12:15 AM


profileImage Answered by:- bhanu

You can generate random string using following code

(function() {
		var randomString = function(length) {
			
			var text = "";
		
			var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
			
			for(var i = 0; i < length; i++) {
			
				text += possible.charAt(Math.floor(Math.random() * possible.length));
			
			}
			
			return text;
		}

		// call function random string with length
		var rand= randomString(10);
		
		// insert random string to the field
		var elem = document.getElementById("randomString").value = rand;
		
	})();
2
At:- 3/7/2018 7:55:29 AM


profileImage Answered by:- manish

You can simply use the code below to generate random string in JS

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

in the above code, we have length of "6" characters, you can change length to "7" or "5" depending on your random string requirement.

In the above code, you can expect to see duplicate after 50,000 unique random string.

OR

If required you can also generate UUID, based on time-stamp, which can be unique.

function generateUUIDUsingMathRandom() { 
    var d = new Date().getTime();//Timestamp
    var d2 = (performance && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16;//random number between 0 and 16
        if(d > 0){//Use timestamp until depleted
            r = (d + r)%16 | 0;
            d = Math.floor(d/16);
        } else {//Use microseconds since page-load if supported
            r = (d2 + r)%16 | 0;
            d2 = Math.floor(d2/16);
        }
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

Generating GUID/UUID using Javascript (Various ways)

Thanks.

2
At:- 4/29/2022 2:33:35 PM
Thanks, it is helpful. 0
By : Vinnu - at :- 5/27/2022 7:50:48 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use