Generating random strings is always necessary when working with things like voucher or password generation, and so today’s quick JavaScript function looks at returning a specified length of string containing a a selection of randomly selected characters and numbers.

The function works by specifying a string containing all the characters you wish to be used in your randomly generated string. Using the random() function and mixing it up a little to generate essentially a character position, we can grab a character off the previously mentioned character string. Rinse and repeat for the desired length of string, adding everything together to at last come up with your string of random characters.

function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	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;

Nice and random, just like this image.