I think this will work for you:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(5));
Answer from csharptest.net on Stack OverflowProgramiz
programiz.com › javascript › examples › generate-random-strings
JavaScript Program to Generate Random String
// program to generate random strings // declare all characters const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; function generateString(length) { let result = ' '; const charactersLength = characters.length; for ( let i = 0; i < length; i++ ) { result += ...
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().
Generate random string/characters in JavaScript
This is as clean as it will get. It is fast too, http://jsperf.com/ay-random-string. More on stackoverflow.com
Random alpha-numeric string in JavaScript? - Stack Overflow
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? More on stackoverflow.com
Random string generator with easy syntax and many complex options.
That's a very cool project. Good job! More on reddit.com
Random String
Add the strings to an array const words = ['jon','jack','jill'] Math.random() generates a random number between 0-1 in Javascript. Math.floor() rounds a number down to an interger. let randomIndex = Math.floor(Math.random()*words.length + 1) Then access the string from the array, based on the random index. console.log(words[randomIndex]) More on reddit.com
Videos
06:09
How to Generate a RANDOM STRING in JavaScript and HTML - YouTube
03:29
How to Generate Random String in Javascript - YouTube
12:47
Javascript Project for Beginners | Code a random strings generator ...
10:53
The Fastest Way To Generate Random Strings in JavaScript - YouTube
13:48
How to Generate Random Numbers in JavaScript | Math.random() ...
01:43
How to Generate a Random String in JavaScript (Secure & Simple ...
Top answer 1 of 16
3768
I think this will work for you:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(5));
2 of 16
3232
//Can change 7 to 2 for longer results.
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);
Note: The above algorithm has the following weaknesses:
- It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.
- It depends deeply on the algorithm used to stringify floating point numbers, which is horrifically complex. (See the paper "How to Print Floating-Point Numbers Accurately".)
Math.random()may produce predictable ("random-looking" but not really random) output depending on the implementation. The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.- Even if it produced 6 uniformly random, unpredictable characters, you can expect to see a duplicate after generating only about 50,000 strings, due to the birthday paradox. (sqrt(36^6) = 46656)
npm
npmjs.com › package › random-string-generator
random-string-generator - npm
March 3, 2025 - Random string's length, default is 12. random(); // 'qCCm2Yoyycjm' or others random(12); // 'qCCm2Yoyycjm' or others · You can generate different variant of strings based on the choices available, default is 'alphanumeric':
» npm install random-string-generator
Top answer 1 of 16
3768
I think this will work for you:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(5));
2 of 16
3232
//Can change 7 to 2 for longer results.
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);
Note: The above algorithm has the following weaknesses:
- It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.
- It depends deeply on the algorithm used to stringify floating point numbers, which is horrifically complex. (See the paper "How to Print Floating-Point Numbers Accurately".)
Math.random()may produce predictable ("random-looking" but not really random) output depending on the implementation. The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.- Even if it produced 6 uniformly random, unpredictable characters, you can expect to see a duplicate after generating only about 50,000 strings, due to the birthday paradox. (sqrt(36^6) = 46656)
GitHub
gist.github.com › 6174 › 6062387
Generate a random string in JavaScript In a short and fast way! · GitHub
const idString = async (string_length) => { var random_str = ""; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZqeytrpolkadjsghfgmnbzxcvnQPOWEYRKASJHDGFMNBCVX--___-_jsfhrlg-_124903564576986483658fgh4sdfh687e4h897WETHJ68F7G4688471877GFHJFFGJ87469857468746hfghwrtiyj4598yhdjkhgnk"; for (let index = 0; index < string_length; index++) { random_str += characters.charAt( Math.floor(Math.random() * characters.length) ); } let string = `${random_str}`; console.log(string); return string; }; ... const generateID = (stringLength = 20) => { let randomStr = ""; const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZqe
Medium
medium.com › @modos.m98 › creating-a-seeded-random-string-generator-in-javascript-3165aae1c2d5
Creating a Seeded Random String Generator in JavaScript | by Mohammad Hossein Mazandaranian | Medium
August 10, 2025 - Enter seeded randomness. By using a seed value, you can generate the same sequence every time you run your code with that seed. In this article, we’ll build a simple seeded random string generator in JavaScript. We’ll start with a seeded pseudo-random number generator (PRNG), then use it to create customizable random strings.
Scaler
scaler.com › home › topics › random string generator in javascript
Random String Generator in JavaScript - Scaler Topics
January 1, 2024 - Concatenate the selected characters to form the random string. ... This code defines a function generateRandomString that takes a length parameter for the desired string length and a charset parameter for the character set to choose from.
Javatpoint
javatpoint.com › random-string-generator-using-javascript
Random String Generator using JavaScript - javatpoint
Random String Generator using JavaScript with javascript tutorial, introduction, javascript oops, application of javascript, loop, variable, objects, map, typedarray etc.
Medium
medium.com › @python-javascript-php-html-css › how-to-generate-a-random-5-character-string-in-javascript-f35accc66cbd
How to Use JavaScript to Create a Random String of Five Characters
August 24, 2024 - The function returns the generated string, which is then logged to the console. This approach ensures higher randomness and security, making it suitable for applications requiring stronger guarantees against predictability. ... // Function to generate a random 5-character string function generateRandomString(length) { const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let result = ''; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } console.log(generateRandomString(5));
npm
npmjs.com › package › randomstring
randomstring - npm
January 10, 2025 - Library to help you create random strings. ... var randomstring = require("randomstring"); randomstring.generate(); // >> "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT" randomstring.generate(7); // >> "xqm5wXX" randomstring.generate({ length: 12, charset: 'alphabetic' }); // >> "AqoTIzKurxJi" randomstring.generate({ charset: 'abc' }); // >> "accbaabbbbcccbccccaacacbbcbbcbbc" randomstring.generate({ charset: ['numeric', '!'] }); // >> "145132!87663611567!2486211!07856" randomstring.generate({ charset: 'abc' }, cb); // >> "cb(generatedString) {}"
» npm install randomstring
Published Jan 10, 2025
Version 1.3.1
Author Elias Klughammer
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);
}
Sling Academy
slingacademy.com › article › ways-to-generate-random-strings-in-javascript
4 Ways to Generate Random Strings in JavaScript - Sling Academy
February 25, 2023 - It helps us randomly select characters from the character’s string (that includes all letters and numbers) by using the ... const generateRandomString = (length) => { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }; console.log(generateRandomString(5)); console.log(generateRandomString(30));