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?
-
29Shortest way? Is this a code golf question? – Greg Hewgill May 23 '12 at 19:55
-
6Haha, no! This isn't a contest for who can pack their code the tightest. I've seen some solutions that list the entire character set in a string, which seemed wasteful. Just looking for something not much longer than it needs to be. – Pavel May 23 '12 at 20:02
-
5@Pavel that's what code golf is.... – Naftali May 23 '12 at 20:04
-
2@Pavel http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript – Sony Mathew Jul 24 '14 at 05:42
-
11@neal removing redundancy is good engineering practice, code golf is writing the smallest amount of code (often involving single character variables, side effects, and other poor practices). They're similar but very distinct. – mikemaccana Jan 09 '16 at 16:53
-
If you are using `Lodash` or `Underscore`, then http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript/36734713#36734713 – vineet Apr 20 '16 at 05:43
24 Answers
I just came across this as a really nice and elegant solution:
Math.random().toString(36).slice(2)
Notes on this implementation:
- This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros.
- It won't generate capital letters, only lower-case and numbers.
- Because the randomness comes from
Math.random()
, the output may be predictable and therefore not necessarily unique. - Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.

- 41,353
- 8
- 121
- 105

- 9,668
- 4
- 45
- 57
-
-
1@kimos Good catch. One way to solve that is to just try again. For example: `function rStr() { var s=Math.random().toString(36).slice(2); return s.length===16 ? s : rStr(); }` – rescuecreative Feb 21 '14 at 14:23
-
9Do you have a busy site? Then sometimes it will generate a random number less than `0.000001`. The `toString()` for a lower number is something like `3.4854687E-7` and your random alphanumeric string will be `4854687E-7` which is no longer alphanumeric. That no longer meets OP's requirements – Adrian Pronk May 13 '14 at 23:08
-
1Can you explain how this works? Why are you passing `36` to `toString`? – user3871 Feb 26 '15 at 02:46
-
3toString takeas a radix param, the "base" in which the integer is translated to string. The easiest to grasp this, I think is `var a = 5;a.toString(2)` ; will return the number 5 in binary format, so `101`. full docs at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString – JAR.JAR.beans Feb 26 '15 at 09:31
-
-
-
1For those who may not realize it, you can get shorter strings by increasing the number you feed to `.slice(2)` (e.g. `.slice(5)`) – rinogo Nov 09 '17 at 16:27
-
1@rinogo I appended a .slice(0, lengthIWant) to it to get a shorter length. – Jim Factor Feb 26 '18 at 22:02
-
Clean but risky, it's depends on the version of V8 you're running. for those who asked how it's work, you can see it here:https://tc39.es/ecma262/#sec-numeric-types-number-tostring – Doron Segal Mar 01 '21 at 23:06
-
Nice answer! For string length > 16. We can call recursively and concatenate. `const rStr = (l) => { const s = Math.random().toString(36).slice(2, l + 2); const d = l - s.length; return !d ? s : `${s}${rStr(d)}`; };` This also allows for stripping numbers with something like `.replace(/[^a-z]/gi, '')` – Davey Apr 28 '22 at 12:38
-
1
-
If you only want to allow specific characters, you could also do it like 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'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:
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 as described below you could do something like this:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
-
I really like the second approach. I tried using it, and it seems to have some problems. As you can see from [THIS](http://cl.ly/image/3z370u0W2U0L) screenshot, it sometimes generates strings that aren't the specified length. I put your `randomString(..)` function in a `for(var i=0;i<50;i++){}` loop that generated 50 random strings, and the last one is three characters long. I also told it to write to the document 50 times like so: `document.write(randomString(8, '#aA!') + "");` – Matthew Jul 15 '14 at 03:24
-
1@Matthew That might be your browser picking up an unintentional false tag in the output string. Check the output source and see if there are a few wayward <'s and >'s in there causing trouble. – Nimphious Jul 24 '14 at 13:49
-
3Well, there is a statistical bug here. `Math.round(Math.random() * (chars.length - 1))` will give half probability for `[0]` and for `[chars.length-1]` than for the rest of characters, as to round to them are needed respectively a number in intervals `[0, 0.5)` and `[chars.length-2+0.5, chars.length-1)` of size 0.5, while the rest of characters need `[index-0.5, index+0.5)` of size 1. The correct indexing function should be: `parseInt(Math.random() * chars.length)` as the upper bound for random() is excluded and `chars.length` will be no reached: http://www.w3schools.com/jsref/jsref_random.asp – axelbrz Apr 06 '15 at 10:33
-
@axelbrz That's a good point but your implementation is bad, your learning reference is one you should never use, and there's a bug in yours too. There's a chance Math.random() returns 1, and in that instance you'll get the upper bound which we don't want. So lets use math functions instead and extract only the fractional portion of `Math.random()` to filter out the possibility of 1.0, which should give us an almost entirely uniform probability. A bettter implementation would be: `Math.floor((Math.random() % 1) * chars.length)` – Nimphious Apr 10 '15 at 01:50
-
5@Nimphious Please give me your references. `Math.random()` will never return 1. It's returning value is in `[0, 1)` that means 0 is included and 1 is excluded. Here are four different and important independent sources: Mozilla: http://goo.gl/BQGZiG ; Microsoft MSDN (IE): http://goo.gl/MPuCJM ; w3schools: http://goo.gl/qXrK7P ; Stackoverflow: http://goo.gl/CUoyIT (`num` being `1`) and http://goo.gl/D9az3C and http://goo.gl/0mERDq . What are you sources to assume 1 is a possible value for Math.random() ? Because it's not. – axelbrz Apr 14 '15 at 03:22
-
In the other hand, something positive of your last comment is that `Math.floor` seems to be faster than `parseInt` so that's a good one; but the `%1` is still unnecessary, so `Math.floor(Math.random() * chars.length)` will be enough and even statistically uniform. If not, please share a reference that invalidates the ones of Mozilla, Microsoft, w2schools and Stackoverflow I've share. Thanks. – axelbrz Apr 14 '15 at 03:24
-
Ahh your right @axelbrz, I haven't checked the references in years. But yeah I did some perf testing and Math.floor is definitely faster than parseInt, often by a factor of 100 or more. As far as references, w3schools has a really bad track record for accuracy and keeping up with standards changes, as well as a bad history of poor coding practices so I've avoided them like the plague. MDN, MSDN, SO and the like are all great though. – Nimphious Apr 16 '15 at 12:52
-
5I took the liberty to fix the statistical bug in the code. Because this is the top result on google for 'random javascript string' its a shame to have a buggy answer. – Iftah Dec 01 '15 at 10:21
-
@Iftah Yeah you're not wrong, with the previous version the min/max values only had 50% of the probability of the others, plus this version is simpler. Win win. – Nimphious Dec 02 '15 at 14:47
-
Getting Z2K3TMUJW23(E+11) with IE when the length is 11. Actually getting scientific notation for every number above 10. No issue with chrome. – TheBakker Apr 12 '17 at 10:17
-
@TheBakker Which version of IE? The solution is to be simple and if possible elegant, not necessarily backwards compatible. Backwards compatibility is an exercise for the reader and dependent on project requirements. – Nimphious Apr 13 '17 at 20:43
-
Yeah I went with a another less classy solution. It's an IE 11 though so not really that old. The scientific annotation got added when doing toString(36) for some reason. – TheBakker Apr 14 '17 at 08:51
-
I have used this method, But how do i include only 4 alphanumeric characters in the password – tkamath99 Sep 07 '20 at 09:38
-
If you need a truly alphanumeric string this won't work as sometimes it will return a number... if you are using this to create object keys the expected key order will be wrong if you have a mixture of keys that are strings and numbers. Try calling RandomString(4, '#aA'); 1000 times, occasionally you will get a number. – user2677034 Nov 25 '22 at 19:53
-
@user2677034 Numbers are perfectly valid "alphanumeric strings", if you want to guarantee both letters and numbers then you'd obviously want to adjust your approach, or if lazy just brute force it with some kind of output validation retry loop if it's not performance critical, since the odds of getting only letters or numbers more than a handful of times in a row are pretty insignificant. – Nimphious Jan 16 '23 at 23:11
UPDATED: One-liner solution, for random 20 characters (alphanumeric lowercase):
Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');
Or shorter with lodash:
_.times(20, () => _.random(35).toString(36)).join('');

- 22,632
- 6
- 47
- 54
Another variation of answer suggested by JAR.JAR.beans
(Math.random()*1e32).toString(36)
By changing multiplicator 1e32
you can change length of random string.

- 433
- 4
- 6
-
2Nice answer, that helped me. with 1e32 ive got 19 chars long string and with 1e64 ive got 40. Thanks a lot! – Bogdan Le Jul 13 '15 at 18:55
-
3@BogdanLewis Note that string length it is not guaranteed. Meaning 1e64 not always produce 40 characters length string, however it will be close to 40. – he-yaeh Jul 13 '15 at 19:21
-
i got it! i was looking for simple solution that generates long random strings (close to 40 chars) – Bogdan Le Jul 13 '15 at 19:43
-
good answer . however, it does not generate CAPITAL (uppercase) letters – Abdennour TOUMI Nov 20 '16 at 19:25
Or to build upon what Jar Jar suggested, this is what I used on a recent project (to overcome length restrictions):
var randomString = function (len, bits)
{
bits = bits || 36;
var outStr = "", newStr;
while (outStr.length < len)
{
newStr = Math.random().toString(bits).slice(2);
outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
}
return outStr.toUpperCase();
};
Use:
randomString(12, 16); // 12 hexadecimal characters
randomString(200); // 200 alphanumeric characters

- 9,911
- 8
- 53
- 66
This is cleaner
Math.random().toString(36).substr(2, length)
Example
Math.random().toString(36).substr(2, 5)

- 5,220
- 3
- 17
- 21
-
5
-
1but you can do your logic something like this... console.log(Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)) + Math.random().toString(36).substring(2, 15)); :-) – Parth Raval Apr 22 '19 at 11:29
function randomString(len) {
var p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return [...Array(len)].reduce(a=>a+p[~~(Math.random()*p.length)],'');
}
Summary:
- Create an array of the size we want (because there's no
range(len)
equivalent in javascript.- For each element in the array: pick a random character from
p
and add it to a string- Return the generated string.
Some explanation:
[...Array(len)]
Array(len) or new Array(len) creates an array with undefined pointer(s). One-liners are going to be harder to pull off. The Spread syntax conveniently defines the pointers (now they point to undefined objects!).
.reduce(
Reduce the array to, in this case, a single string. The reduce functionality is common in most languages and worth learning.
a=>a+...
We're using an arrow function.
a
is the accumulator. In this case it's the end-result string we're going to return when we're done (you know it's a string because the second argument to the reduce function, the initialValue is an empty string: ''
). So basically: convert each element in the array with p[~~(Math.random()*p.length)]
, append the result to the a
string and give me a
when you're done.
p[...]
p
is the string of characters we're selecting from. You can access chars in a string like an index (E.g., "abcdefg"[3]
gives us "d"
)
~~(Math.random()*p.length)
Math.random()
returns a floating point between [0, 1) Math.floor(Math.random()*max)
is the de facto standard for getting a random integer in javascript. ~
is the bitwise NOT operator in javascript.
~~
is a shorter, arguably sometimes faster, and definitely funner way to say Math.floor(
Here's some info

- 1,593
- 1
- 18
- 22
-
1While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Badacadabra Jun 21 '17 at 20:09
I think the following is the simplest solution which allows for a given length:
Array(myLength).fill(0).map(x => Math.random().toString(36).charAt(2)).join('')
It depends on the arrow function syntax.

- 27,060
- 21
- 118
- 148

- 1,647
- 1
- 16
- 29
for 32 characters:
for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)

- 14,787
- 6
- 68
- 57
Random character:
String.fromCharCode(i); //where is an int
Random int:
Math.floor(Math.random()*100);
Put it all together:
function randomNum(hi){
return Math.floor(Math.random()*hi);
}
function randomChar(){
return String.fromCharCode(randomNum(100));
}
function randomString(length){
var str = "";
for(var i = 0; i < length; ++i){
str += randomChar();
}
return str;
}
var RandomString = randomString(32); //32 length string

- 144,921
- 39
- 244
- 303
-
This includes a whole bunch of non-alphanumeric characters. An example (what I got on the first try): `M&I56aP=H K?
– sveti petar Dec 08 '14 at 14:42 -
i got `] 4INBKJ\\`_5.(/"__X,,K"\)]` many chars are not usable and were stripped by SO – RozzA Jan 18 '17 at 21:27
-
Null bytes (String.fromCharCode(0)) cause all sorts of problems in many languages/databases/environments. Codes 33-126 produce the visible ASCII characters. – JasonWoof Apr 03 '18 at 02:12
Using lodash:
function createRandomString(length) {
var chars = "abcdefghijklmnopqrstufwxyzABCDEFGHIJKLMNOPQRSTUFWXYZ1234567890"
var pwd = _.sampleSize(chars, length || 12) // lodash v4: use _.sampleSize
return pwd.join("")
}
document.write(createRandomString(8))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
-
2`_.sample()` returns only one char. I think you mean `_.sampleSize()` – karliwson Apr 20 '17 at 18:19
-
2Using lodash to generate a random CSS hex color: `_.sampleSize("abcdef0123456789", 6).join("")` – XåpplI'-I0llwlg'I - Oct 05 '17 at 04:29
-
-
It's not a good idea to use `_.sampleSize` to generate random strings. It will only generate _unique_ elements (it will never repeat a character). This reduces the entropy. – matangover Dec 13 '21 at 11:04
-
Also, in the above example if `length > 62` the returned string will always be 62 characters long, due to the size of `chars`. – matangover Dec 13 '21 at 11:10
Random Key Generator
keyLength argument is the character length you want for the key
function keyGen(keyLength) {
var i, key = "", characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var charactersLength = characters.length;
for (i = 0; i < keyLength; i++) {
key += characters.substr(Math.floor((Math.random() * charactersLength) + 1), 1);
}
return key;
}
keyGen(12)
"QEt9mYBiTpYD"

- 585
- 1
- 6
- 17
var randomString = function(length) {
var str = '';
var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
'');
var charsLen = chars.length;
if (!length) {
length = ~~(Math.random() * charsLen);
}
for (var i = 0; i < length; i++) {
str += chars[~~(Math.random() * charsLen)];
}
return str;
};

- 82
- 4
When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid.toUpperCase();
}

- 141
- 2
- 10
-
You of course can shorten or lengthen the string to have as many or as few characters as you want. – nlv Jan 19 '15 at 18:36
-
1Here is where I most likely found the code: http://stackoverflow.com/a/8809472/988540 – nlv Jan 19 '15 at 18:45
This function should give a random string in any length.
function randString(length) {
var l = length > 25 ? 25 : length;
var str = Math.random().toString(36).substr(2, l);
if(str.length >= length){
return str;
}
return str.concat(this.randString(length - str.length));
}
I've tested it with the following test that succeeded.
function test(){
for(var x = 0; x < 300000; x++){
if(randString(x).length != x){
throw new Error('invalid result for len ' + x);
}
}
}
The reason i have chosen 25 is since that in practice the length of the string returned from Math.random().toString(36).substr(2, 25)
has length 25. This number can be changed as you wish.
This function is recursive and hence calling the function with very large values can result with Maximum call stack size exceeded
. From my testing i was able to get string in the length of 300,000 characters.
This function can be converted to a tail recursion by sending the string to the function as a second parameter. I'm not sure if JS uses Tail call optimization

- 3,978
- 3
- 37
- 34
A simple function that takes the length
getRandomToken(len: number): string {
return Math.random().toString(36).substr(2, len);
}
Ff you pass 6 it will generate 6 digit alphanumeric number

- 10,019
- 9
- 74
- 96

- 14,608
- 25
- 132
- 189
-
This function is partially valid. Maximum `len` is 11 in this case. – sobczak.dev Jun 01 '23 at 14:52
Nice and simple, and not limited to a certain number of characters:
let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);
Here's a simple code to generate random string alphabet.
Have a look how this code works.
go(lenthOfStringToPrint);
- Use this function to generate the final string.
var letters = {
1: ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"],
2: ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"]
},i,letter,final="";
random = (max,min) => {
return Math.floor(Math.random()*(max-min+1)+min);
}
function go(length) {
final="",letter="";
for (i=1; i<=length; i++){
letter = letters[random(0,3)][random(0,25)];
final+=letter;
}
return final;
}
I used @Nimphious excellent second approach and found that occasionally the string returned was numeric - not alphanumeric. The solution I used was to test using !isNaN and use recursion to call the function again. Why bother? I was using this function to create object keys, if all the keys are alphanumeric everything sorts properly but if you use numbers as keys mixed with alphanumeric (strings) looping through the object will produce a different order to original order.
function newRandomString(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 += '0123456789';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() *
mask.length)];
/*
we need a string not a number !isNaN(result)) will return true if '1234' or '3E77'
because if we're looping through object keys (created by newRandomString()) and
a number is used and all the other keys are strings then the number will
be first even if it was the 2nd or third key in object
*/
//use recursion to try again
if(!isNaN(result)){
console.log('found a number....:'+result);
return newRandomString(length, chars)
}else{
return result;
}
};
var i=0;
while (i < 1000) {
var a = newRandomString(4, '#$aA');
console.log(i+' - '+a);
//now we're using recursion this won't occur
if(!isNaN(a)){
console.log('=============='+i+' - '+a);
}
i++;
}
console.log('3E77:'+!isNaN('3E77'));//true
console.log('1234:'+!isNaN('1234'));//true
console.log('ab34:'+!isNaN('ab34'));//false

- 624
- 10
- 20
After looking at solutions in answers to this question and other sources, this is the solution that is simplest while allowing for modification of the included characters and selection in the length of the returned result.
// generate random string of n characters
function randomString(length) {
const characters = '0123456789abcdefghijklmnopqrstuvwxyz'; // characters used in string
let result = ''; // initialize the result variable passed out of the function
for (let i = length; i > 0; i--) {
result += characters[Math.floor(Math.random() * characters.length)];
}
return result;
}
console.log(randomString(6));

- 1,252
- 1
- 12
- 19
I needed a longer string and I like @JAR.JAR.beans' elegant answer.
Here is an adjustable one liner that generates a longer string.
Array(100).fill().map(z=>Math.random().toString(36).slice(2)).join("")
You can even change the number 100
to adjust the length of the randomly generated string

- 118
- 9
Use md5 library: https://github.com/blueimp/JavaScript-MD5
The shortest way:
md5(Math.random())
If you want to limit the size to 5:
md5(Math.random()).substr(0, 5)

- 167
- 1
- 6
If you want to specify any set of characters, such as base64 characters, without typing out every single character into an 'abcd...' string, you can do this:
const chars = [['0', 10], ['a', 26], ['A', 26], ['-'], ['_']]
.flatMap(([c, length=1]) =>
Array.from({length}, (_,i) => String.fromCharCode(c.charCodeAt(0)+i)))
const gen = length => Array.from({length},
() => chars[Math.random()*chars.length|0]).join('')
console.log(chars.join(''))
console.log(gen(10))

- 6,358
- 2
- 12
- 27