Random string generation with Javascript

Here is a small but useful function to generate a string with a random number of characters with the help of javascript.

function randomString(min, max) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	if(!min) min = 7;
	if(!max) max = 10;		
	var string_length = Math.floor(Math.random() * (max - min + 1) + min);

	var randomstring = '';
	for (var i=0; i < string_length ; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

Leave a Reply

Your email address will not be published.