What is the shortest way (within reason) to generate a random alphanumeric (uppercase, lowercase and numeric) string to use as a possible unique identifier in JavaScript?
P粉3121957002023-10-13 12:38:49
I just discovered this is a very nice and elegant solution:
Math.random().toString(36).slice(2)
Comments for this implementation:
Math.random()
, the output may be predictable and therefore not necessarily unique. P粉9856865572023-10-13 09:56:40
If you only want to allow specific characters, you can also do this:
function randomString(length, chars) { var result = ''; for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)]; return result; } var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
Here is a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
Another approach is to use a special string to tell the function what type of characters to use. You can do this:
function randomString(length, chars) { var mask = ''; if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; if (chars.indexOf('#') > -1) mask += '0123456789'; if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\'; var result = ''; for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; return result; } console.log(randomString(16, 'aA')); console.log(randomString(32, '#aA')); console.log(randomString(64, '#A!'));
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method described below, you can do the following:
function randomString(length) { return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1); }