我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
这是肯定的
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>
其他回答
如果您使用的是Lodash或Undercore,那么非常简单:
var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');
递归解决方案:
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")
最简单的方法是:
(new Date%9e6).toString(36)
这将基于当前时间生成5个字符的随机字符串。示例输出为4mtxj或4mv90或4mwp1
这样做的问题是,如果您在同一秒内调用它两次,它将生成相同的字符串。
更安全的方法是:
(0|Math.random()*9e6).toString(36)
这将生成一个4或5个字符的随机字符串,总是不同的。示例输出类似于30jzm或1r591或4su1a
在这两种方式中,第一部分生成一个随机数。.toString(36)部分将数字转换为它的base36(字母十进制)表示形式。
随机数值(最多16位)
/**
* Random numeric value (up to 16 digits)
* @returns {String}
*/
function randomUid () {
return String(Math.floor(Math.random() * 9e15))
}
// randomUid() -> "3676724552601324"
",,,,,".replace(/,/g,function (){return "AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa".charAt(Math.floor(Math.random()*62))});