我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
Math.random不适合这种情况
服务器端
使用节点加密模块-
var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');
// "bb5dc8842ca31d4603d6aa11448d1654"
生成的字符串将是您生成的随机字节的两倍长;编码为十六进制的每个字节是2个字符。20字节将是40个十六进制字符。
客户端
使用浏览器的加密模块crypto.getRandomValues-
通过crypto.getRandomValues()方法,可以获得加密的强随机值。作为参数给出的数组用随机数填充(在其密码意义上是随机的)。
//dec2hex::整数->字符串//即0-255->“00”-“f”功能dec2hex(dec){return dec.toString(16).padStart(2,“0”)}//generateId::整数->字符串函数生成器ID(len){var arr=新Uint8Array((len||40)/2)window.crypto.getRandomValues(arr)return Array.from(arr,dec2hex).join(“”)}console.log(generateId())//“82defcf324571e70b0521d79cce2bf3ffccd69”console.log(generateId(20))//“c1a050a4cd1556948d41”
分步控制台示例-
> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
> arr
Uint8Array(4) [ 0, 0, 0, 0 ]
> window.crypto
Crypto { subtle: SubtleCrypto }
> window.crypto.getRandomValues()
TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed
> window.crypto.getRandomValues(arr)
Uint8Array(4) [ 235, 229, 94, 228 ]
对于IE11支持,您可以使用-
(window.crypto || window.msCrypto).getRandomValues(arr)
有关浏览器覆盖范围,请参阅https://caniuse.com/#feat=getrandomvalues
客户端(旧浏览器)
如果您必须支持旧浏览器,请考虑像uuid这样的东西-
const uuid = require("uuid");
const id = uuid.v4();
// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"
其他回答
//创建一个长度为10的随机代码,您可以随意更改它
function createRandomCode(length) {
let randomCodes = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++ ) {
randomCodes += characters.charAt(Math.floor(Math.random() * charactersLength))
}
console.log("your reference code is: ".toLocaleUpperCase() + randomCodes);
};
createRandomCode(10)
以下代码将使用npm包加密随机字符串生成大小为[a-zA-Z0-9]的加密安全随机字符串。使用以下方法安装:
npm install crypto-random-string
要在集合[a-zA-Z0-9]中获得30个字符的随机字符串:
const cryptoRandomString = require('crypto-random-string');
cryptoRandomString({length: 100, type: 'base64'}).replace(/[/+=]/g,'').substr(-30);
摘要:我们正在替换一个大的随机base64字符串中的/,+,=,并获取最后N个字符。
PS:在子字符串中使用-N
仅仅一个简单的map或reduce实现就足够了:
const charset: string =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const random1: string = [...Array(5)]
.map((_) => charset[Math.floor(Math.random() * charset.length)])
.join("");
const random2: string = [...Array(5)]
.reduce<string>(
(acc) => acc += charset[Math.floor(Math.random() * charset.length)],
"",
);
//返回随机字母
let alpha = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
console.log(alpha.charAt(Math.floor(Math.random() * alpha.length)));
递归解决方案:
function generateRamdomId (seedStr) {
const len = seedStr.length
console.log('possibleStr', seedStr , ' len ', len)
if(len <= 1){
return seedStr
}
const randomValidIndex = Math.floor(Math.random() * len)
const randomChar = seedStr[randomValidIndex]
const chunk1 = seedStr.slice(0, randomValidIndex)
const chunk2 = seedStr.slice(randomValidIndex +1)
const possibleStrWithoutRandomChar = chunk1.concat(chunk2)
return randomChar + generateRamdomId(possibleStrWithoutRandomChar)
}
你可以用你想要的种子,如果你不想,不要重复字符。实例
generateRandomId("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")