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 Overflow
🌐
Programiz
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().
Discussions

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
🌐 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
🌐 stackoverflow.com
Random string generator with easy syntax and many complex options.
That's a very cool project. Good job! More on reddit.com
🌐 r/dartlang
4
23
December 5, 2021
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
🌐 r/learnjavascript
9
1
December 21, 2021
🌐
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
    
Published   Mar 03, 2025
Version   1.0.7
Author   yuhenabc
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › random-string-generator-using-javascript
Random String Generator using JavaScript - GeeksforGeeks
August 5, 2025 - Learn how to create a random string generator using JavaScript. This guide covers generating random strings, including alphanumeric characters and passwords, with practical examples.
🌐
Vultr Docs
docs.vultr.com › javascript › examples › generate-random-string
JavaScript Program to Generate Random String | Vultr Docs
November 27, 2024 - Generating random strings in JavaScript is straightforward with the use of Math.random() and a basic loop mechanism. By customizing the function, you can adapt the random string generator for various purposes, including testing, unique identifiers, ...
🌐
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 - Starting from 11/12, it will start introducing letters. So to get a fully random string: ... const generateRandomString = function(length=6){ return Math.random().toString(20).substr(2, length) }
Find elsewhere
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › generate-random-characters-numbers-in-javascript
Generate Random Characters & Numbers in JavaScript - GeeksforGeeks
August 5, 2025 - The function Str_Random generates a random string of specified length, combining characters and numbers.
🌐
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.
🌐
Medium
medium.com › @randomstr › generating-random-strings-in-javascript-and-its-frameworks-118cb1c9cba7
Generating Random Strings in JavaScript and Its Frameworks | by Random STR | Medium
December 1, 2023 - In this post, we’ll explore how to generate random strings in plain JavaScript and extend this functionality to popular JavaScript frameworks.
🌐
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);
}
🌐
Zipy
zipy.ai › blog › generate-random-string-characters-in-javascript
generate random string characters in javascript
April 12, 2024 - JavaScript, with its rich set of features and capabilities, provides multiple pathways to achieve randomness. Here, we delve into several approaches to generate random strings, each suited for different requirements and scenarios.
🌐
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));
🌐
Attacomsian
attacomsian.com › blog › javascript-generate-random-string
How to generate a random string in JavaScript
October 23, 2020 - To generate a fully random string, you should pass 16 or greater as a radix value to toString():