我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
",,,,,".replace(/,/g,function (){return "AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa".charAt(Math.floor(Math.random()*62))});
其他回答
您可以使用base64:
function randomString(length)
{
var rtn = "";
do {
rtn += btoa("" + Math.floor(Math.random() * 100000)).substring(0, length);
}
while(rtn.length < length);
return rtn;
}
试试这个,我每次都用的:
函数myFunction(){var hash=“abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789”;var random8=“”;对于(变量i=0;i<5;i++){random8+=哈希[parseInt(Math.random()*hash.length)];}控制台日志(random8);document.getElementById(“demo”).innerHTML=“您的5个字符串==>”+random8;} <!DOCTYPE html><html><body><p>单击按钮生成5个字符的随机字符串</p><button onclick=“myFunction()”>单击我</button><p id=“demo”></p></body></html>
生成安全的随机字母数字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”
如果您是在node js上开发,最好使用crypto。下面是实现randomStr()函数的示例
const crypto = require('crypto');
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
.fill(null)
.map(() => charset.charAt(crypto.randomInt(charset.length)))
.join('');
如果您不是在服务器环境中工作,只需更换随机数生成器:
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
.fill(null)
.map(() => charset.charAt(Math.floor(Math.random() * charset.length)))
.join('');
function randomString (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
while (strLength--) { // (note, fixed typo)
result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
}
return result.join('');
}
这是最干净的了。它也很快,http://jsperf.com/ay-random-string.