我想要一个5个字符串,其中包含从集合中随机选择的字符[a-zA-Z0-9]
。
用JavaScript做到这一点的最佳方法是什么?
我想要一个5个字符串,其中包含从集合中随机选择的字符[a-zA-Z0-9]
。
用JavaScript做到这一点的最佳方法是什么?
How about something like this: Date.now().toString(36)
Not very random, but short and quite unique every time you call it.
This works for sure
<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>
I did not find a clean solution for supporting both lowercase and uppercase characters.
Lowercase only support:
Math.random().toString(36).substr(2, 5)
Building on that solution to support lowercase and uppercase:
Math.random().toString(36).substr(2, 5).split('').map(c => Math.random() < 0.5 ? c.toUpperCase() : c).join('');
Change the 5
in substr(2, 5)
to adjust to the length you need.
To meet requirement [a-zA-Z0-9] and length=5 use
btoa(Math.random()).substr(5, 5);
Lowercase letters, uppercase letters, and numbers will occur.
You can loop through an array of items and recursively add them to a string variable, for instance if you wanted a random DNA sequence:
function randomDNA(len) {
len = len || 100
var nuc = new Array("A", "T", "C", "G")
var i = 0
var n = 0
s = ''
while (i <= len - 1) {
n = Math.floor(Math.random() * 4)
s += nuc[n]
i++
}
return s
}
console.log(randomDNA(5));
Here are some easy one liners. Change new Array(5)
to set the length.
0-9a-z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})
0-9a-zA-Z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});
The simplest way is:
(new Date%9e6).toString(36)
This generate random strings of 5 characters based on the current time. Example output is 4mtxj
or 4mv90
or 4mwp1
The problem with this is that if you call it two times on the same second, it will generate the same string.
The safer way is:
(0|Math.random()*9e6).toString(36)
This will generate a random string of 4 or 5 characters, always diferent. Example output is like 30jzm
or 1r591
or 4su1a
In both ways the first part generate a random number. The .toString(36)
part cast the number to a base36 (alphadecimal) representation of it.
A newer version with es6 spread operator:
[...Array(30)].map(() => Math.random().toString(36)[2]).join('')
30
is arbitrary number, you can pick any token length you want36
is the maximum radix number you can pass to numeric.toString(), which means all numbers and a-z lowercase letters2
is used to pick the 3th index from the random string which looks like this: "0.mfbiohx64i"
, we could take any index after 0.
function randomstring(L) {
var s = '';
var randomchar = function() {
var n = Math.floor(Math.random() * 62);
if (n < 10) return n; //1-10
if (n < 36) return String.fromCharCode(n + 55); //A-Z
return String.fromCharCode(n + 61); //a-z
}
while (s.length < L) s += randomchar();
return s;
}
console.log(randomstring(5));
返回恰好5个随机字符,与此处找到的一些评分最高的答案相反。
Math.random().toString(36).substr(2, 5);
最紧凑的解决方案,因为slice
它比短substring
。从字符串末尾减去可以避免该random
函数生成的浮点符号:
Math.random().toString(36).slice(-5);
甚至
(+new Date).toString(36).slice(-5);
更新:使用btoa
方法添加了另一种方法:
btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);
// Using Math.random and Base 36:
console.log(Math.random().toString(36).slice(-5));
// Using new Date and Base 36:
console.log((+new Date).toString(36).slice(-5));
// Using Math.random and Base 64 (btoa):
console.log(btoa(Math.random()).slice(0, 5));
// Using new Date and Base 64 (btoa):
console.log(btoa(+new Date).slice(-7, -2));
console.log(btoa(+new Date).substr(-7, 5));
let r = Math.random().toString(36).substring(7);
console.log("random", r);
注意:以上算法具有以下缺点:
Math.random()
根据实现的不同,可能会产生可预测的(“看上去很随机”但不是真正随机的)输出。当您需要保证唯一性或不可预测性时,生成的字符串不适合。
This one combines many of the answers give.
I have been using it for 1 month with great results.