Explain Codes LogoExplain Codes Logo

Generate random string/characters in JavaScript

javascript
random-string
crypto
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 4, 2024
TLDR

To create a random string in JavaScript, we define a function that generates characters from a predefined set in a loop until the desired string length is met. We utilize Math.random() for random selection and charAt() to fetch the character.

function randomString(len) { let result = '', chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; while (len--) result += chars[Math.random() * chars.length | 0]; return result; } console.log(randomString(10)); // Example output: 'Nf92mD0s2G'

This compact solution returns a random alphanumeric string of specified length.

Single-liner for quick random strings

For a quicker solution to generate a 5-character alphanumeric string, you can use this one-liner:

let str = Math.random().toString(36).substring(2, 7); console.log(str); // Example: '4j1tr' - almost as random as my ex's mood swings!

Here, we use toString(36) to convert the number into a base-36 string, followed by substring() to trim the string to our desired length.

Crypto for secure random strings

Need higher security? Try crypto.getRandomValues to generate a cryptographically strong random string.

function secureRandomString(len) { const randomVals = crypto.getRandomValues(new Uint8Array(len)); return Array.from(randomVals, byte => `0${byte.toString(16)}`.slice(-2)).join(''); } console.log(secureRandomString(10)); // Example: '7e1d3e5b1f' - now that's a secure password!

Noticeably stronger than Math.random(), this method offers adequate randomness suitable for cryptographic purposes.

Ensuring uniqueness and compatibility

Addressing sequence repetition

Though Math.random() allows a likelihood of repetitions after ~50K iterations, it is apt for non-critical tasks needing lightweight solutions. But for applications demanding a more robust solution, stronger cryptographic methods are our go-to.

Catering to legacy browsers

While handling legacy browsers like IE11, it is recommended to use (window.crypto || window.msCrypto).getRandomValues to ensure maximum compatibility. For browser support validation, resources like caniuse.com are a great help.

Achieving unbiased randomness

Given the float-point nature of Math.random(), distribution is non-uniform, which could introduce bias. This bias is inconsequential for the majority of applications, but for critical applications demanding unbiased randomness, cryptographic tools or third-party string generation libraries are preferred.

Usage tips and optimizations

Array.map() and Array.fill() for code brevity

To adopt a cleaner syntax, you can use Array(N).fill().map():

let randomStr = Array(10).fill().map(() => Math.random().toString(36)[2]).join(''); console.log(randomStr); // Example: 'gb72e4bm9u' - watch out, it's a wild string!

Hexadecimal random strings

Here's how you can generate a random hexadecimal string:

let hexString = [...Array(10)].map(() => Math.floor(Math.random() * 16).toString(16)).join(''); console.log(hexString); // Example: '89fd25b0aa' - no hexes, just hex strings!

crypto usage in Node.js

For Node.js environments, make use of crypto.randomBytes:

const crypto = require('crypto'); function nodeRandomString(len) { return crypto.randomBytes(len).toString('hex'); } console.log(nodeRandomString(10)); // Example: '782a3b9d5f' - seems like Node.js's litecoin mining!