function rndStr() {x=Math.random().toString(36).substring(7).substr(0,5);while (x.length!=5){x=Math.random().toString(36).substring(7).substr(0,5);}return x;}
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('');
function randomString(length) {if ( length <= 0 ) return "";var getChunk = function(){var i, //index iteratorrand = Math.random()*10e16, //execute random oncebin = rand.toString(2).substr(2,10), //random binary sequencelcase = (rand.toString(36)+"0000000000").substr(0,10), //lower case random stringucase = lcase.toUpperCase(), //upper case random stringa = [lcase,ucase], //position them in an array in index 0 and 1str = ""; //the chunk stringb = 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 nextreturn str;},str = ""; //the result stringwhile ( str.length < length )str += getChunk();str = str.substr(0,length);return str;}
String::add_Random_Letters = (size )->charSet = 'abcdefghijklmnopqrstuvwxyz'@ + (charSet[Math.floor(Math.random() * charSet.length)] for i in [1..size]).join('')
可用于
value = "abc_"value_with_exta_5_random_letters = value.add_Random_Letters(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));
// functional prerequisitesconst U = f=> f (f)const Y = U (h=> f=> f (x=> h (h) (f) (x)))const comp = f=> g=> x=> f (g (x))const foldk = Y (h=> f=> y=> ([x, ...xs])=>x === undefined ? y : f (y) (x) (y=> h (f) (y) (xs)))const fold = f=> foldk (y=> x=> k=> k (f (y) (x)))const map = f=> fold (y=> x=> [...y, f (x)]) ([])const char = x=> String.fromCharCode(x)const concat = x=> y=> y.concat(x)const concatMap = f=> comp (fold (concat) ([])) (map (f))const irand = x=> Math.floor(Math.random() * x)const sample = xs=> xs [irand (xs.length)]
// range : make a range from x to y; [x...y]// Number -> Number -> [Number]const range = Y (f=> r=> x=> y=>x > y ? r : f ([...r, x]) (x+1) (y)) ([])
// srand : make random string from list or ascii code ranges// [(Range a)] -> Number -> [a]const srand = comp (Y (f=> z=> rs=> x=>x === 0 ? z : f (z + sample (rs)) (rs) (x-1)) ([])) (concatMap (map (char)))
// idGenerator : make an identifier of specified length// Number -> Stringconst idGenerator = srand ([range (48) (57), // include 0-9range (65) (90), // include A-Zrange (97) (122) // include a-z])
console.log (idGenerator (6)) //=> TT688Xconsole.log (idGenerator (10)) //=> SzaaUBlpI1console.log (idGenerator (20)) //=> eYAaWhsfvLDhIBID1xRh
在我看来,如果不添加神奇的、做太多事情的功能,很难击败idGenerator的清晰度。
略有改善可能是
// ord : convert char to ascii code// Char -> Numberconst ord = x => x.charCodeAt(0)
// idGenerator : make an identifier of specified length// Number -> Stringconst idGenerator = srand ([range (ord('0')) (ord('9')),range (ord('A')) (ord('Z')),range (ord('a')) (ord('z'))])
function getRandomId(length) {if (!length) {return '';}
const possible ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';let array;
if ('Uint8Array' in self && 'crypto' in self && length <= 65536) {array = new Uint8Array(length);self.crypto.getRandomValues(array);} else {array = new Array(length);
for (let i = 0; i < length; i++) {array[i] = Math.floor(Math.random() * 62);}}
let result = '';
for (let i = 0; i < length; i++) {result += possible.charAt(array[i] % 62);}
return result;}
function myFunction() {var hash = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";var random8 = '';for(var i = 0; i < 5; i++){random8 += hash[parseInt(Math.random()*hash.length)];}console.log(random8);document.getElementById("demo").innerHTML = "Your 5 character string ===> "+random8;}
<!DOCTYPE html><html><body>
<p>Click the button to genarate 5 character random string .</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body></html>
function makeId(length) {var id = '';var rdm62;while (length--) {// Generate random integer between 0 and 61, 0|x works for Math.floor(x) in this caserdm62 = 0 | Math.random() * 62;// Map to ascii codes: 0-9 to 48-57 (0-9), 10-35 to 65-90 (A-Z), 36-61 to 97-122 (a-z)id += String.fromCharCode(rdm62 + (rdm62 < 10 ? 48 : rdm62 < 36 ? 55 : 61))}return id;}
function randStr(len) {let s = '';while (s.length < len) s += Math.random().toString(36).substr(2, len - s.length);return s;}
// usageconsole.log(randStr(50));
这个函数的好处是可以得到不同长度的随机字符串,它保证了字符串的长度。
大小写敏感所有字符:
function randStr(len) {let s = '';while (len--) s += String.fromCodePoint(Math.floor(Math.random() * (126 - 33) + 33));return s;}
// usageconsole.log(randStr(50));
自定义Chars
function randStr(len, chars='abc123') {let s = '';while (len--) s += chars[Math.floor(Math.random() * chars.length)];return s;}
// usageconsole.log(randStr(50));console.log(randStr(50, 'abc'));console.log(randStr(50, 'aab')); // more a than b
function randomStringGenerator(stringLength) {var randomString = ""; // Empty value of the selective variableconst allCharacters = "'`~!@#$%^&*()_+-={}[]:;\'<>?,./|\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'"; // listing of all alpha-numeric letterswhile (stringLength--) {randomString += allCharacters.substr(Math.floor((Math.random() * allCharacters.length) + 1), 1); // selecting any value from allCharacters varible by using Math.random()}return randomString; // returns the generated alpha-numeric string}
console.log(randomStringGenerator(10));//call function by entering the random string you want
或
console.log(Date.now())// it will produce random thirteen numeric character value every time.console.log(Date.now().toString().length)// print length of the generated string
const DEFAULT_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
function getRandomCharFromAlphabet(alphabet: string): string {return alphabet.charAt(Math.floor(Math.random() * alphabet.length));}
function generateId(idDesiredLength: number, alphabet = DEFAULT_ALPHABET): string {/*** Create n-long array and map it to random chars from given alphabet.* Then join individual chars as string*/return Array.from({length: idDesiredLength}).map(() => {return getRandomCharFromAlphabet(alphabet);}).join('');}
generateId(5); // jNVv7
function randomString(length) {let chars = [], output = '';for (let i = 32; i < 127; i ++) {chars.push(String.fromCharCode(i));}for (let i = 0; i < length; i ++) {output += chars[Math.floor(Math.random() * chars.length )];}return output;}
let testRnd = n => console.log(`num dec: ${n}, num base36: ${n.toString(36)}, string: ${n.toString(36).substr(2, 5)}`);
[Math.random(),// and much more less than 0.5...0.5,0.50077160493827161,0.5015432098765432,0.5023148148148148,0.5030864197530864,// and much more....0.9799597050754459].map(n=>testRnd(n));
console.log('... and so on');
Each of below example (except first) numbers result with less than 5 characters (which not meet OP question requirements)
Here is "generator" which allows manually find such numbers
function base36Todec(hex) {hex = hex.split(/\./);return (parseInt(hex[1],36))*(36**-hex[1].length)+ +(parseInt(hex[0],36));}
function calc(hex) {let dec = base36Todec(hex);msg.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${dec.toString(36)}</b>`}
function calc2(dec) {msg2.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${(+dec).toString(36)}</b>`}
let init="0.za1";inp.value=init;calc(init);
Type number in range 0-1 using base 36 (0-9,a-z) with less than 5 digits after dot<br><input oninput="calc(this.value)" id="inp" /><div id="msg"></div><br>If above <i>hex test</i> give more digits than 5 after dot - then you can try to copy dec number to below field and join some digit to dec num right side and/or change last digit - it sometimes also produce hex with less digits<br><input oninput="calc2(this.value)" /><br><div id="msg2"></div>
const c = new class { [Symbol.toPrimitive]() { return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0) } };console.log(c+c+c+c+c);// AgMnz
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 charseeds = [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 resultresult += String.fromCharCode(seeds[Math.floor(Math.random() * 3)])}
return result}
/* This method is very fast and is suitable into intensive loops *//* Return a mix of uppercase and lowercase chars */
/* This will always output the same hash, since the salt array is the same */console.log(btoa(String.fromCharCode(...new Uint8Array( [0,1,2,3] ))))
/* Always output a random hex hash of here: 30 chars */console.log(btoa(String.fromCharCode(...new Uint8Array( Array(30).fill().map(() => Math.round(Math.random() * 30)) ))))