JavaScript 中的随机字母数字字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10726909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random alpha-numeric string in JavaScript?
提问by Pavel
What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?
在 JavaScript 中生成随机字母数字(大写、小写和数字)字符串以用作可能唯一标识符的最短方法(在合理范围内)是什么?
回答by JAR.JAR.beans
I just came across this as a really nice and elegant solution:
我刚刚发现这是一个非常好的和优雅的解决方案:
Math.random().toString(36).slice(2)
Notes on this implementation:
关于这个实现的注意事项:
- This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros.
- It won't generate capital letters, only lower-case and numbers.
- Because the randomness comes from
Math.random()
, the output may be predictable and therefore not necessarily unique. - Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.
- 由于浮点字符串化会删除尾随零,这将生成一个长度介于 0 到 12 个字符之间的字符串,通常为 11 个字符。
- 它不会生成大写字母,只会生成小写字母和数字。
- 因为随机性来自
Math.random()
,输出可能是可预测的,因此不一定是唯一的。 - 即使假设是一个理想的实现,输出也最多有 52 位的熵,这意味着在生成大约 7000 万个字符串后,您可以期待重复。
回答by Nimphious
If you only want to allow specific characters, you could also do it like this:
如果您只想允许特定字符,您也可以这样做:
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
Here's a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
这是一个 jsfiddle 来演示:http: //jsfiddle.net/wSQBx/
Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:
另一种方法是使用一个特殊的字符串来告诉函数使用什么类型的字符。你可以这样做:
function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
}
console.log(randomString(16, 'aA'));
console.log(randomString(32, '#aA'));
console.log(randomString(64, '#A!'));
Fiddle: http://jsfiddle.net/wSQBx/2/
小提琴:http: //jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method as described below you could do something like this:
或者,要使用如下所述的 base36 方法,您可以执行以下操作:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
回答by he-yaeh
Another variation of answer suggested by JAR.JAR.beans
JAR.JAR.beans 建议的另一种答案变体
(Math.random()*1e32).toString(36)
By changing multiplicator 1e32
you can change length of random string.
通过更改乘数,1e32
您可以更改随机字符串的长度。
回答by Josh Mc
Or to build upon what Jar Jar suggested, this is what I used on a recent project (to overcome length restrictions):
或者根据 Jar Jar 的建议,这是我在最近的一个项目中使用的(为了克服长度限制):
var randomString = function (len, bits)
{
bits = bits || 36;
var outStr = "", newStr;
while (outStr.length < len)
{
newStr = Math.random().toString(bits).slice(2);
outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
}
return outStr.toUpperCase();
};
Use:
用:
randomString(12, 16); // 12 hexadecimal characters
randomString(200); // 200 alphanumeric characters
回答by DS.
One-liner with lodash, for random 20 characters (alphanumeric lowercase):
带有 lodash 的单行,用于随机 20 个字符(字母数字小写):
_.times(20, () => _.random(35).toString(36)).join('');
回答by Diego Mello
This is cleaner
这个更干净
Math.random().toString(36).substr(2, length)
Example
例子
Math.random().toString(36).substr(2, 5)
回答by László Monda
I think the following is the simplest solution which allows for a given length:
我认为以下是允许给定长度的最简单的解决方案:
Array(myLength).fill(0).map(x => Math.random().toString(36).charAt(2)).join('')
It depends on the arrow function syntax.
这取决于箭头函数语法。
回答by Collin Anderson
for 32 characters:
对于 32 个字符:
for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)
回答by roundar
function randomString(len) {
var p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return [...Array(len)].reduce(a=>a+p[~~(Math.random()*p.length)],'');
}
Summary:
概括:
- Create an array of the size we want (because there's no
range(len)
equivalent in javascript.- For each element in the array: pick a random character from
p
and add it to a string- Return the generated string.
- 创建一个我们想要的大小的数组(因为
range(len)
在 javascript 中没有等价物。- 对于数组中的每个元素:从中选择一个随机字符
p
并将其添加到字符串中- 返回生成的字符串。
Some explanation:
一些解释:
[...Array(len)]
[...Array(len)]
Array(len) or new Array(len) creates an array with undefined pointer(s). One-liners are going to be harder to pull off. The Spread syntaxconveniently defines the pointers (now they point to undefined objects!).
Array(len) 或 new Array(len)创建一个带有未定义指针的数组。单线将更难实现。在传播语法方便地定义指针(现在他们指向不确定的对象!)。
.reduce(
.reduce(
Reducethe array to, in this case, a single string. The reduce functionality is common in most languagesand worth learning.
在这种情况下,将数组缩减为单个字符串。reduce 功能在大多数语言中都很常见,值得学习。
a=>a+...
a=>a+...
We're using an arrow function.
我们正在使用箭头函数。
a
is the accumulator.In this case it's the end-result string we're going to return when we're done (you know it's a string because the second argument to the reduce function, the initialValueis an empty string: ''
). So basically: convert each element in the array with p[~~(Math.random()*p.length)]
, append the result to the a
string and give me a
when you're done.
a
是累加器。在这种情况下,它是我们完成后将返回的最终结果字符串(您知道它是一个字符串,因为 reduce 函数的第二个参数,initialValue是一个空字符串:)''
。所以基本上:用 转换数组中的每个元素p[~~(Math.random()*p.length)]
,将结果附加到a
字符串并a
在完成后给我。
p[...]
p[...]
p
is the string of characters we're selecting from. You can access chars in a string like an index (E.g., "abcdefg"[3]
gives us "d"
)
p
是我们从中选择的字符串。您可以像索引一样访问字符串中的字符(例如,"abcdefg"[3]
给我们"d"
)
~~(Math.random()*p.length)
~~(Math.random()*p.length)
Math.random()
returns a floating point between [0, 1) Math.floor(Math.random()*max)
is the de facto standard for getting a random integer in javascript. ~
is the bitwise NOT operator in javascript.
~~
is a shorter, arguably sometimes faster, and definitely funner way to say Math.floor(
Here's some info
Math.random()
返回 [0, 1) 之间的浮点数Math.floor(Math.random()*max)
是在 javascript 中获取随机整数的事实标准。~
是 javascript 中的按位非运算符。
~~
是一种更短的、可以说有时更快、而且绝对更有趣的表达方式Math.floor(
这是一些信息
回答by Naftali aka Neal
Random character:
随机字符:
String.fromCharCode(i); //where is an int
Random int:
随机整数:
Math.floor(Math.random()*100);
Put it all together:
把它们放在一起:
function randomNum(hi){
return Math.floor(Math.random()*hi);
}
function randomChar(){
return String.fromCharCode(randomNum(100));
}
function randomString(length){
var str = "";
for(var i = 0; i < length; ++i){
str += randomChar();
}
return str;
}
var RandomString = randomString(32); //32 length string