我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
这个小巧的小把戏怎么样?
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var stringLength = 5;
function pickRandom() {
return possible[Math.floor(Math.random() * possible.length)];
}
var randomString = Array.apply(null, Array(stringLength)).map(pickRandom).join('');
您需要Array.apply来将空数组变为未定义的数组。
如果您正在为ES2015进行编码,那么构建阵列会简单一些:
var randomString = Array.from({ length: stringLength }, pickRandom).join('');
其他回答
从字符a-Za-z0-9中随机化字符串的另一种好方法:
function randomString(length) {
if ( length <= 0 ) return "";
var getChunk = function(){
var i, //index iterator
rand = Math.random()*10e16, //execute random once
bin = rand.toString(2).substr(2,10), //random binary sequence
lcase = (rand.toString(36)+"0000000000").substr(0,10), //lower case random string
ucase = lcase.toUpperCase(), //upper case random string
a = [lcase,ucase], //position them in an array in index 0 and 1
str = ""; //the chunk string
b = rand.toString(2).substr(2,10);
for ( i=0; i<10; i++ )
str += a[bin[i]][i]; //gets the next character, depends on the bit in the same position as the character - that way it will decide what case to put next
return str;
},
str = ""; //the result string
while ( str.length < length )
str += getChunk();
str = str.substr(0,length);
return str;
}
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)
}
这是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
您可以使用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>