What’s the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?
Advertisement
Answer
If you only want to allow specific characters, you could also do it like this:
JavaScript
x
7
1
function randomString(length, chars) {
2
var result = '';
3
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
4
return result;
5
}
6
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
7
Here’s a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:
JavaScript
1
15
15
1
function randomString(length, chars) {
2
var mask = '';
3
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
4
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5
if (chars.indexOf('#') > -1) mask += '0123456789';
6
if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";'<>?,./|\';
7
var result = '';
8
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
9
return result;
10
}
11
12
console.log(randomString(16, 'aA'));
13
console.log(randomString(32, '#aA'));
14
console.log(randomString(64, '#A!'));
15
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method as described below you could do something like this:
JavaScript
1
4
1
function randomString(length) {
2
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
3
}
4