我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
function generate(length) {
var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"];
var IDtext = "";
var i = 0;
while (i < length) {
var letterIndex = Math.floor(Math.random() * letters.length);
var letter = letters[letterIndex];
IDtext = IDtext + letter;
i++;
}
console.log(IDtext)
}
其他回答
生成包含aA zZ和0-9字符集合的随机字符串。只需使用长度参数调用此函数。
所以要回答这个问题:generateRandomString(5)
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
//Generate seeds array, that will be the bag from where randomly select generated char
seeds = [
Math.floor(Math.random() * 10) + 48,
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
//Choise randomly from seeds, convert to char and append to result
result += String.fromCharCode(seeds[Math.floor(Math.random() * 3)])
}
return result
}
生成不带数字的字符串的版本:
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
seeds = [
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
result += String.fromCharCode(seeds[Math.floor(Math.random() * 2)])
}
return result
}
如果可以使用库,Chance.js可能会有所帮助:http://chancejs.com/#string
我想这会对你有用:
函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));
这里有一种不同的方法,按基数固定长度,不使用RegExp替换lack(基于@bendytree的答案);
function rand(base) {
// default base 10
base = (base >= 2 && base <= 36) ? base : 10;
for (var i = 0, ret = []; i < base; i++) {
ret[i] = ((Math.random() * base) | 0).toString(base)
// include 0-9a-zA-Z?
// [Math.random() < .5 ? 'toString' : 'toUpperCase']();
}
return ret.join('');
}
最简单的方法是:
(new Date%9e6).toString(36)
这将基于当前时间生成5个字符的随机字符串。示例输出为4mtxj或4mv90或4mwp1
这样做的问题是,如果您在同一秒内调用它两次,它将生成相同的字符串。
更安全的方法是:
(0|Math.random()*9e6).toString(36)
这将生成一个4或5个字符的随机字符串,总是不同的。示例输出类似于30jzm或1r591或4su1a
在这两种方式中,第一部分生成一个随机数。.toString(36)部分将数字转换为它的base36(字母十进制)表示形式。