Generate a string of random characters

Generate a string of random characters

技术背景

在开发过程中,经常会遇到需要生成随机字符串的场景,例如生成唯一的标识符、临时密码等。JavaScript 提供了多种方法来实现这一需求,不同的方法适用于不同的场景。

实现步骤

1. 使用 Math.random() 生成随机字符串

1
2
3
4
5
6
7
8
9
10
11
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. 基于 Math.random() 的其他简洁方法

1
2
3
4
5
6
7
8
9
10
// 返回 5 个随机字符
Math.random().toString(36).slice(-5);

// 基于当前时间生成 5 个随机字符
(+new Date).toString(36).slice(-5);

// 使用 btoa 方法
btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);

3. 服务器端(Node.js)使用 crypto 模块

1
2
3
4
5
6
7
8
9
// ESM 导入方式
import * as crypto from "node:crypto";
const id = crypto.randomBytes(20).toString('hex');
console.log(id);

// CJS 导入方式
const crypto = require("crypto");
const id = crypto.randomBytes(20).toString('hex');
console.log(id);

4. 客户端(浏览器)使用 crypto 模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 使用 randomUUID 方法
const id = window.crypto.randomUUID();
console.log(id);

// 使用 getRandomValues 方法
function dec2hex(dec) {
return dec.toString(16).padStart(2, "0");
}

function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join('');
}

console.log(generateId());
console.log(generateId(20));

5. 旧浏览器支持

1
2
3
const uuid = require("uuid");
const id = uuid.v4();
console.log(id);

核心代码

以下是几种不同方式生成随机字符串的核心代码:

自定义字符集生成随机字符串

1
2
3
4
5
6
7
8
9
10
11
12
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz, randomPoz + 1);
}
return randomString;
}

var randomValue = randomString(5);
var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');

生成指定长度的字母数字随机字符串

1
2
3
4
5
6
7
8
9
10
11
function randomString(len) {
var str = '';
for (var i = 0; i < len; i++) {
var rand = Math.floor(Math.random() * 62);
var charCode = rand += rand > 9 ? (rand < 36 ? 55 : 61) : 48;
str += String.fromCharCode(charCode);
}
return str;
}

console.log(randomString(10));

最佳实践

  • 安全性要求高的场景:使用 crypto 模块,它提供了更安全的随机数生成方法,适用于生成安全令牌、密码等。
  • 简单场景:可以使用 Math.random() 方法,代码简洁,但生成的随机数安全性较低,不适合用于安全敏感的场景。
  • 跨浏览器兼容性:如果需要支持旧浏览器,可以使用 uuid 库。

常见问题

1. Math.random() 生成的随机数不够随机

Math.random() 生成的是伪随机数,在某些情况下可能不够随机,不适合用于安全敏感的场景。可以使用 crypto 模块来生成更安全的随机数。

2. 生成的字符串长度不稳定

使用 Math.random().toString(36) 时,由于浮点数转换为字符串时可能会去掉末尾的零,导致生成的字符串长度不稳定。可以通过填充和截取的方式来确保字符串长度固定。

3. 重复问题

由于随机数的有限性,在大量生成随机字符串时可能会出现重复的情况。可以通过增加字符串长度或使用更安全的随机数生成方法来降低重复的概率。


Generate a string of random characters
https://119291.xyz/posts/2025-05-12.generate-a-string-of-random-characters/
作者
ww
发布于
2025年5月12日
许可协议