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
0
: 172 At:- 2/27/2018 12:32:48 PM
javascript random string generation






2 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
At:- 2/28/2018 7:23:21 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





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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly