我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
"12345".split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');
//or
String.prototype.rand = function() {return this.split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');};
将生成长度为第一个/调用字符串的随机字母数字字符串
其他回答
以下代码将使用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
如果任何人对一个一次性分配内存的单行程序(虽然为了方便起见,没有格式化为这样)感兴趣(但请注意,对于小字符串,这实际上无关紧要),下面是如何做到的:
Array.apply(0, Array(5)).map(function() {
return (function(charset){
return charset.charAt(Math.floor(Math.random() * charset.length))
}('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));
}).join('')
您可以用所需字符串的长度替换5。感谢@AriyaHidayat在本文中提供的解决方案,该解决方案解决了array(5)创建的稀疏数组上的map函数不工作的问题。
",,,,,".replace(/,/g,function (){return "AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa".charAt(Math.floor(Math.random()*62))});
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.
这是Coffeescapet版本的一行代码
genRandomString = (length,set) -> [0...length].map( -> set.charAt Math.floor(Math.random() * set.length)).join('')
用法:
genRandomString 5, 'ABCDEFTGHIJKLMNOPQRSTUVWXYZ'
输出:
'FHOOV' # random string of length 5 in possible set A~Z