我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
如果可以使用库,Chance.js可能会有所帮助:http://chancejs.com/#string
其他回答
为了从一个数组中生成一个散列作为一个盐,[0,1,2,3]在这个例子中,通过这种方式,我们可以稍后检索散列来填充一个条件。
只需输入一个随机数组,或作为数组的额外安全和快速指纹。
/*该方法非常快速,适用于密集循环*//*返回大小写混合字符*//*这将始终输出相同的哈希,因为salt数组是相同的*/控制台日志(btoa(String.fromCharCode(…新Uint8Array([0,1,2,3])))/*始终输出此处的随机十六进制哈希:30个字符*/控制台日志(btoa(String.fromCharCode(…new Uint8Array(Array(30).fill().map(()=>Math.round(Math.random()*30)))))
使用加密API中的HMAC,了解更多信息:https://stackoverflow.com/a/56416039/2494754
您可以使用base64:
function randomString(length)
{
var rtn = "";
do {
rtn += btoa("" + Math.floor(Math.random() * 100000)).substring(0, length);
}
while(rtn.length < length);
return rtn;
}
您可以使用Web Crypto的API:
console.log(self.crypto.getRandomValues(新Uint32Array(1))[0])
(此处为原始答案)
最重要的是,所有的答案都是完美的。但我要补充的是,生成任何随机字符串值都非常好而且快速
函数randomStringGenerator(stringLength){var randomString=“”;//选择变量的空值const allCharacters=“`~!@#$%^&*()_+-={}[]:;\'<>?,./|\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlmnopqrstuvwxyz0123456789'”;//所有字母数字字母列表while(stringLength--){randomString+=allCharacters.substr(Math.floor((Math.random()*allCharacters.length)+1),1);//使用Math.random()从所有字符变量中选择任意值}return randomString;//返回生成的字母数字字符串}console.log(randomStringGenerator(10))//通过输入所需的随机字符串来调用函数
or
console.log(Date.now())//它每次都会产生随机的十三个数字字符值。console.log(Date.now().toString().length)//打印生成字符串的长度
生成安全的随机字母数字Base-62字符串:
函数生成UID(长度){return window.btoa(String.fromCharCode(…window.crypto.getRandomValues(新Uint8Array(长度*2))).replace(/[+/]/g,“”).substring(0,长度);}console.log(生成UID(22));//“yFg3Upv2cE9cKOXd7hHwWp”console.log(生成UID(5));//“YQGzP”