Générer des chaînes/caractères aléatoires en JavaScript

Mots clés : javascriptstringrandomjavascript

meilleur 5 Réponses Générer des chaînes/caractères aléatoires en JavaScript

vote vote

90

function makeid(length) {     var result           = '';     var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';     var charactersLength = characters.length;     for ( var i = 0; i < length; i++ ) {       result += characters.charAt(Math.floor(Math.random() *   charactersLength));    }    return result; }  console.log(makeid(5));
vote vote

86

//Can change 7 to 2 for longer results. let r = (Math.random() + 1).toString(36).substring(7); console.log("random", r);
vote vote

78

var crypto = require("crypto"); var id = crypto.randomBytes(20).toString('hex');  // "bb5dc8842ca31d4603d6aa11448d1654" 
var uuid = require("uuid"); var id = uuid.v4();  // "110ec58a-a0f2-4ac4-8393-c866d813b8d1" 
// dec2hex :: Integer -> String // i.e. 0-255 -> '00'-'ff' function dec2hex (dec) {   return dec.toString(16).padStart(2, "0") }  // generateId :: Integer -> String function generateId (len) {   var arr = new Uint8Array((len || 40) / 2)   window.crypto.getRandomValues(arr)   return Array.from(arr, dec2hex).join('') }  console.log(generateId()) // "82defcf324571e70b0521d79cce2bf3fffccd69"  console.log(generateId(20)) // "c1a050a4cd1556948d41"
> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255) > arr Uint8Array(4) [ 0, 0, 0, 0 ]  > window.crypto Crypto { subtle: SubtleCrypto }  > window.crypto.getRandomValues() TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed  > window.crypto.getRandomValues(arr) Uint8Array(4) [ 235, 229, 94, 228 ] 
(window.crypto || window.msCrypto).getRandomValues(arr) 
vote vote

67

Math.random().toString(36).substr(2, 5); 
vote vote

57

(Math.random().toString(36)+'00000000000000000').slice(2, N+2) 
Array(N+1).join((Math.random().toString(36)+'00000000000000000').slice(2, 18)).slice(0, N) 
var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
Array(N).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join(''); 
Array.apply(null, Array(N)).map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join(''); 

Questions similaires