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);
}
🌐
TutorialsPoint
tutorialspoint.com › home › lodash › lodash random function
Lodash Random Function
January 20, 2021 - Produces a random number between the inclusive lower and upper bounds. If only one argument is provided a number between 0 and the given number is returned. If floating is true, or either lower or upper are floats, a floating-point number is ...
🌐
Lodash
lodash.com › docs
Lodash Documentation
Gets n random elements at unique keys from collection up to the size of collection. ... Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. ... Gets the size of collection by returning its length for array-like values or the number of own enumerable string keyed ...
🌐
GeeksforGeeks
geeksforgeeks.org › lodash-_-random-method
Lodash _.random() Method | GeeksforGeeks
October 31, 2023 - Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
🌐
Lodash
lodash.info › doc › random
random - Lodash documentation
_.random(0, 5); // => an integer between 0 and 5 _.random(5); // => also an integer between 0 and 5 _.random(5, true); // => a floating-point number between 0 and 5 _.random(1.2, 5.2); // => a floating-point number between 1.2 and 5.2
🌐
npm
npmjs.com › package › lodash.random
lodash.random - npm
The lodash method `_.random` exported as a module.. Latest version: 3.2.0, last published: 9 years ago. Start using lodash.random in your project by running `npm i lodash.random`. There are 149 other projects in the npm registry using lodash.random.
      » npm install lodash.random
    
Published   Aug 13, 2016
Version   3.2.0
Author   John-David Dalton
🌐
Educative
educative.io › answers › how-to-get-a-random-element-from-an-array-using-lodash
How to get a random element from an array using Lodash
In Lodash, you can get a random element from an array using the _.sample() method or the _.sampleSize() method.
🌐
CodeToFun
codetofun.com › lodash › number-random
Lodash _.random() Number Method | CodeToFun
October 30, 2024 - Optimize randomness in JavaScript with Lodash's _.random() method. Generate random numbers efficiently, tailoring results with optional parameters. Enhance precision and control in your code for seamless number generation. Elevate your programming with Lodash's reliable and versatile randomization ...
🌐
GitHub
github.com › lodash › lodash › issues › 3572
Feature Requests: Pick one or more random entries out of an array, string, or object · Issue #3572 · lodash/lodash
November 26, 2017 - Pick one or more random entries out of an array, string, or object. Use case: string // in Bulls and Cows game function genSecret() { return _.shuffle("0123456789".split("")).slice(0, 4).join("") } // with new method function genSecret()...
Published   Jan 02, 2018
Find elsewhere
🌐
JSFiddle
jsfiddle.net › dawidrylko › 8haxhvps
Get random item from an array [Lodash] - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
🌐
GitHub
gist.github.com › daaniam › 8b00c9741e98ca6eea60b8428a2a6d0f
bruno scripts · GitHub
const _ = require('lodash'); // Function to generate random string function randStr(length) { return _.join(_.times(length, () => _.random(35).toString(36)), ''); } // Function to generate a random integer with a specified number of digits function randInt(digits) { const min = Math.pow(10, digits - 1); const max = Math.pow(10, digits) - 1; return _.random(min, max); } // Set vars bru.setVar("randStr8", randStr(8)) bru.setVar("randInt4", randInt(4)) bru.setVar("randEmail", randStr(8) + "@example.com")
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-get-a-random-element-from-an-array-using-lodash
How to get a Random Element from an Array using Lodash ? | GeeksforGeeks
May 3, 2024 - In this approach, we are using _.sample from the Lodash library to randomly select an element from the array, and then we log the selected element res to the console.
🌐
GitHub
github.com › lodash › lodash › issues › 3289
No mechanism to use seeded random generation · Issue #3289 · lodash/lodash
April 24, 2017 - Currently, methods that expose random behaviour, like sample, use the internal Math.random() function, which is unseeded. Not being able to optionally enforce deterministic behaviour in a functiona...
Published   Jul 31, 2017
🌐
Docs-lodash
docs-lodash.com › v4 › random
_.random – Lodash Docs v4.17.11
_.random(0, 5); // => an integer between 0 and 5 _.random(5); // => also an integer between 0 and 5 _.random(5, true); // => a floating-point number between 0 and 5 _.random(1.2, 5.2); // => a floating-point number between 1.2 and 5.2
🌐
GitHub
gist.github.com › 6174 › 6062387
Generate a random string in JavaScript In a short and fast way! · GitHub
This is my version. Generate random string with numbers, lower and upper case.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-sample-method
Lodash _.sample() Method - GeeksforGeeks
September 3, 2024 - Lodash's _.sample() method randomly selects and returns a single element from a collection (array, object, or string).
🌐
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.