admin管理员组文章数量:1126307
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?
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?
Share Improve this question asked May 23, 2012 at 19:54 PavelPavel 5,6628 gold badges38 silver badges47 bronze badges 7- 29 Shortest way? Is this a code golf question? – Greg Hewgill Commented May 23, 2012 at 19:55
- 6 Haha, no! This isn't a contest for who can pack their code the tightest. I've seen some solutions that list the entire character set in a string, which seemed wasteful. Just looking for something not much longer than it needs to be. – Pavel Commented May 23, 2012 at 20:02
- 5 @Pavel that's what code golf is.... – Naftali Commented May 23, 2012 at 20:04
- 2 @Pavel stackoverflow.com/questions/1349404/… – Sony Mathew Commented Jul 24, 2014 at 5:42
- 11 @neal removing redundancy is good engineering practice, code golf is writing the smallest amount of code (often involving single character variables, side effects, and other poor practices). They're similar but very distinct. – mikemaccana Commented Jan 9, 2016 at 16:53
26 Answers
Reset to default 468I 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.
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/
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/
Alternatively, to use the base36 method as described below you could do something like this:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
UPDATED: One-liner solution, for random 20 characters (alphanumeric lowercase):
Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');
Or shorter with lodash:
_.times(20, () => _.random(35).toString(36)).join('');
Another variation of answer suggested by JAR.JAR.beans
(Math.random()*1e32).toString(36)
By changing multiplicator 1e32
you can change length of random string.
This is cleaner
Math.random().toString(36).substr(2, length)
Example
Math.random().toString(36).substr(2, 5)
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.
Some explanation:
[...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 syntax conveniently defines the pointers (now they point to undefined objects!).
.reduce(
Reduce the array to, in this case, a single string. The reduce functionality is common in most languages and worth learning.
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 initialValue is 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.
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"
)
~~(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
Or to build upon what Jar Jar suggested, this is what I used on a recent project (to overcome length restrictions):
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
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.
for 32 characters:
for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)
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
Fiddle: http://jsfiddle.net/maniator/QZ9J2/
Using lodash:
function createRandomString(length) {
var chars = "abcdefghijklmnopqrstufwxyzABCDEFGHIJKLMNOPQRSTUFWXYZ1234567890"
var pwd = _.sampleSize(chars, length || 12) // lodash v4: use _.sampleSize
return pwd.join("")
}
document.write(createRandomString(8))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Random Key Generator
keyLength argument is the character length you want for the key
function keyGen(keyLength) {
var i, key = "", characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var charactersLength = characters.length;
for (i = 0; i < keyLength; i++) {
key += characters.substr(Math.floor((Math.random() * charactersLength) + 1), 1);
}
return key;
}
keyGen(12)
"QEt9mYBiTpYD"
A simple function that takes the length
getRandomToken(len: number): string {
return Math.random().toString(36).substr(2, len);
}
Ff you pass 6 it will generate 6 digit alphanumeric number
var randomString = function(length) {
var str = '';
var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
'');
var charsLen = chars.length;
if (!length) {
length = ~~(Math.random() * charsLen);
}
for (var i = 0; i < length; i++) {
str += chars[~~(Math.random() * charsLen)];
}
return str;
};
When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid.toUpperCase();
}
Fiddle: http://jsfiddle.net/nlviands/fNPvf/11227/
This function should give a random string in any length.
function randString(length) {
var l = length > 25 ? 25 : length;
var str = Math.random().toString(36).substr(2, l);
if(str.length >= length){
return str;
}
return str.concat(this.randString(length - str.length));
}
I've tested it with the following test that succeeded.
function test(){
for(var x = 0; x < 300000; x++){
if(randString(x).length != x){
throw new Error('invalid result for len ' + x);
}
}
}
The reason i have chosen 25 is since that in practice the length of the string returned from Math.random().toString(36).substr(2, 25)
has length 25. This number can be changed as you wish.
This function is recursive and hence calling the function with very large values can result with Maximum call stack size exceeded
. From my testing i was able to get string in the length of 300,000 characters.
This function can be converted to a tail recursion by sending the string to the function as a second parameter. I'm not sure if JS uses Tail call optimization
const randomString = (length) =>
Array(length)
.fill('')
.map(() => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' [Math.floor(Math.random() * 62)])
.join('')
console.log(randomString(32))
Just another one-liner code.
Nice and simple, and not limited to a certain number of characters:
let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);
I needed a longer string and I like @JAR.JAR.beans' elegant answer.
Here is an adjustable one liner that generates a longer string.
Array(100).fill().map(z=>Math.random().toString(36).slice(2)).join("")
You can even change the number 100
to adjust the length of the randomly generated string
Here's a simple code to generate random string alphabet.
Have a look how this code works.
go(lenthOfStringToPrint);
- Use this function to generate the final string.
var letters = {
1: ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"],
2: ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"]
},i,letter,final="";
random = (max,min) => {
return Math.floor(Math.random()*(max-min+1)+min);
}
function go(length) {
final="",letter="";
for (i=1; i<=length; i++){
letter = letters[random(0,3)][random(0,25)];
final+=letter;
}
return final;
}
I used @Nimphious excellent second approach and found that occasionally the string returned was numeric - not alphanumeric. The solution I used was to test using !isNaN and use recursion to call the function again. Why bother? I was using this function to create object keys, if all the keys are alphanumeric everything sorts properly but if you use numbers as keys mixed with alphanumeric (strings) looping through the object will produce a different order to original order.
function newRandomString(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 += '0123456789';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() *
mask.length)];
/*
we need a string not a number !isNaN(result)) will return true if '1234' or '3E77'
because if we're looping through object keys (created by newRandomString()) and
a number is used and all the other keys are strings then the number will
be first even if it was the 2nd or third key in object
*/
//use recursion to try again
if(!isNaN(result)){
console.log('found a number....:'+result);
return newRandomString(length, chars)
}else{
return result;
}
};
var i=0;
while (i < 1000) {
var a = newRandomString(4, '#$aA');
console.log(i+' - '+a);
//now we're using recursion this won't occur
if(!isNaN(a)){
console.log('=============='+i+' - '+a);
}
i++;
}
console.log('3E77:'+!isNaN('3E77'));//true
console.log('1234:'+!isNaN('1234'));//true
console.log('ab34:'+!isNaN('ab34'));//false
After looking at solutions in answers to this question and other sources, this is the solution that is simplest while allowing for modification of the included characters and selection in the length of the returned result.
// generate random string of n characters
function randomString(length) {
const characters = '0123456789abcdefghijklmnopqrstuvwxyz'; // characters used in string
let result = ''; // initialize the result variable passed out of the function
for (let i = length; i > 0; i--) {
result += characters[Math.floor(Math.random() * characters.length)];
}
return result;
}
console.log(randomString(6));
I needed to generate a unique random handle for each user, with the possibility to add a prefix. Here's my solution:
const dictionary = '0123456789abcdefghijklmnopqrstuvwxyz';
const generateRandomHandle = (prefix = 'mike') => {
return Array.from(
{ length: 12 },
(_, index) => prefix[index]?.toLowerCase() ?? dictionary[Math.floor(Math.random() * dictionary.length)],
).join('');
};
const generate = () => {
const handle = generateRandomHandle();
const field = document.getElementById('root');
if (field) {
field.innerHTML = handle;
}
}
<button onclick="generate()">generate</button>
<div id="root"></div>
As a side note, some of these above solutions return unwanted characters (namely apostrophe '
). Not sure why, I couldn't reproduce that behaviour in the browser, but React-Native seems to permit them.
Use md5 library: https://github.com/blueimp/JavaScript-MD5
The shortest way:
md5(Math.random())
If you want to limit the size to 5:
md5(Math.random()).substr(0, 5)
One could just use lodash uniqueId:
_.uniqueId([prefix=''])
Generates a unique ID. If prefix is given, the ID is appended to it.
If you want to specify any set of characters, such as base64 characters, without typing out every single character into an 'abcd...' string, you can do this:
const chars = [['0', 10], ['a', 26], ['A', 26], ['-'], ['_']]
.flatMap(([c, length=1]) =>
Array.from({length}, (_,i) => String.fromCharCode(c.charCodeAt(0)+i)))
const gen = length => Array.from({length},
() => chars[Math.random()*chars.length|0]).join('')
console.log(chars.join(''))
console.log(gen(10))
本文标签: Random alphanumeric string in JavaScriptStack Overflow
版权声明:本文标题:Random alpha-numeric string in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736684666a1947597.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论