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.
Answer from JAR.JAR.beans on Stack Overflow
Top answer
1 of 16
475

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.
2 of 16
379

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);
}
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ generate-random-alpha-numeric-string-in-javascript
Generate random alpha-numeric string in JavaScript - GeeksforGeeks
July 11, 2025 - Declare new variable ans = ' '. Traverse the string in reverse order using for loop. Use JavaScript Math.random() method to generate the random index and multiple with the length of the string.
๐ŸŒ
30 Seconds of Code
30secondsofcode.org โ€บ home โ€บ javascript โ€บ string โ€บ random alphanumeric
Generate a random alphanumeric JavaScript string - 30 seconds of code
March 15, 2024 - In order to generate a random alphanumeric string, you can use Math.random() to generate a random floating-point number and then convert it to a string using Number.prototype.toString() with a radix value of 36.
๐ŸŒ
Envato Tuts+
code.tutsplus.com โ€บ home โ€บ javascript
Generate Random Numbers and Strings in JavaScript | Envato Tuts+
January 31, 2023 - In this tutorial, we learned how to generate random numbers and alphanumeric strings in JavaScript. Generating random integers is easy in JavaScript with the help of the Math.random() method. All we had to do was scale the output so that it ...
๐ŸŒ
DEV Community
dev.to โ€บ hryggrbyr โ€บ generate-a-random-alphanumeric-string-using-javascript-52nn
Generate a random alphanumeric string using JavaScript - DEV Community
April 29, 2021 - For each of those items (.map()), we randomise the number by multiplying it by a randomly generated number between 0 and 1 (x * Math.random()). This is then converted into a two-character string. We only need the first character so let's grab that with charAt(0). You could also use [0] as shorthand. Now we have an Array of twice as many random alphanumeric characters as we asked for.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ generate random string/characters in javascript
Generate random string/characters in JavaScript | Sentry
This function takes in the length of the random string that you want as an argument and then creates a string output where each character is randomly chosen from the chars variable. In this case, the possible characters in the random string are alphanumeric. Random characters are chosen using Math.random(). You can generate variable-length random strings by varying the length of the argument length using Math.random().
๐ŸŒ
Programiz
programiz.com โ€บ javascript โ€บ examples โ€บ generate-random-strings
JavaScript Program to Generate Random String
To understand this example, you ... ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; function generateString(length) { let result = ' '; const charactersLength = characters.length; for ( let i = 0; i < length; i++ ) { result += characters.charAt(Mat...
๐ŸŒ
Codewithmark
codewithmark.com โ€บ easily-generate-random-alphanumeric-string-in-javascript
Easily generate random alphanumeric string in javascript
If you wanted to include alphabets ... random alphanumeric string without repetition in your js, I would recommend you use all the alphabets....
Find elsewhere
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ javascript-random-alphanumeric-string-28568
Generating Random Alphanumeric Strings in JavaScript | LabEx
Generate a random floating-point number using Math.random(). Convert the number to an alphanumeric string using Number.prototype.toString() with a radix value of 36. Remove the integral part and decimal point from each generated number using ...
๐ŸŒ
RSWP Themes
rswpthemes.com โ€บ home โ€บ javascript tutorial โ€บ how to generate random alphanumeric strings in javascript
How To Generate Random Alphanumeric Strings in JavaScript
April 7, 2024 - Method 3: Using the Chance.js Library: Another approach to generate random alphanumeric strings in JavaScript is by utilizing external libraries like Chance.js.
๐ŸŒ
Latenode
community.latenode.com โ€บ other questions โ€บ javascript
How to generate random strings or characters in JavaScript - JavaScript - Latenode Official Community
October 6, 2024 - I need to create a 5-character string made up of randomly selected characters from the set [a-zA-Z0-9]. What is the most effective method to achieve this using JavaScript?
๐ŸŒ
DEV Community
dev.to โ€บ oyetoket โ€บ fastest-way-to-generate-random-strings-in-javascript-2k5a โ€บ comments
[Discussion] Fastest Way to Generate Random Strings in JavaScript โ€” DEV Community
Something like: const generateRandomString = function (length, randomString="") { randomString += Math.random().toString(20).substr(2, length); if (randomString.length > length) return randomString.slice(0, length); return generateRandomStr...
๐ŸŒ
GitHub
gist.github.com โ€บ Dreyer โ€บ 2368164
Generate random alphanumeric string in JavaScript ยท GitHub
why variables s and r are global? another solution for this task: http://javascript-benchmark.info/t/generate-random-string
๐ŸŒ
npm
npmjs.com โ€บ package โ€บ random-string-alphanumeric-generator
random-string-alphanumeric-generator - npm
randomAlphanumeric Generates a random string of given length lettersIncluded optional field which can be one of following all (default): Includes uppercase letters lowercase letters and numbers lowercase: Includes lowercase letters and numbers uppercase: Includes uppercase letters and numbers
      ยป npm install random-string-alphanumeric-generator
    
Published ย  Jun 26, 2021
Version ย  0.12.2
Author ย  Ritesh Chauhan
๐ŸŒ
sebhastian
sebhastian.com โ€บ javascript-random-string
Code recipe: JavaScript random string generator | sebhastian
April 23, 2021 - You can generate a random alphanumeric string with JavaScript by first creating a variable that contains all the characters you want to include in the random string.
๐ŸŒ
DEV Community
dev.to โ€บ oyetoket โ€บ fastest-way-to-generate-random-strings-in-javascript-2k5a
Javascript Random String: Fastest Way to Generate Random Strings in JavaScript - DEV Community
June 2, 2020 - Basically the idea is to use Math.random(), then you can convert it to string and do some simple string manipulation on it. To get random numbers, I would use something like below: ... Fortunate .toString() has a param called radix that you ...
๐ŸŒ
Devassure
devassure.io โ€บ random alpha numeric characters
Random Alpha Numeric Characters | DevAssure
const chars = 'abcdefghijklmno... => chars[Math.floor(Math.random() * chars.length)]).join(''); }; const randomString = generateRandomString(countOfChars); The variable randomString will contain a random alphanumeric string ...
๐ŸŒ
Codemia
codemia.io โ€บ knowledge-hub โ€บ path โ€บ how_can_i_generate_random_alphanumeric_strings
How can I generate random alphanumeric strings?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ javascript โ€บ examples โ€บ generate-random-string
JavaScript Program to Generate Random String | Vultr Docs
November 27, 2024 - ... This generates a random string of 15 characters long, but only using the characters 'a' to 'f' and '1' to '5'. Generating random strings in JavaScript is straightforward with the use of Math.random() and a basic loop mechanism.
๐ŸŒ
CodePen
codepen.io โ€บ thomasxbanks โ€บ pen โ€บ ExZGEKQ
Generate a random Alphanumeric String using JavaScript
<!-- Demo-only code --> <h1>Generate a random<sup>*</sup> Alphanumeric String using JavaScript</h1> <ul></ul> <small> <sup>*</sup> Not actually the most random but good enough for most use-cases.