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.
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);
}
Videos
01:27
How to Generate a Random, Unique, Alphanumeric String - YouTube
03:29
How to Generate Random String in Javascript - YouTube
06:09
How to Generate a RANDOM STRING in JavaScript and HTML - YouTube
How to generate Random Strings using JavaScript
12:47
Javascript Project for Beginners | Code a random strings generator ...
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...
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
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