Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

js generate random string of length

// Naive solution (not recommended)
Math.random().toString(36).slice(2, 7);

// Option 1 (native node js)
var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// Option 2 (3rd party module)
var uuid = require("uuid");
var id = uuid.v4();

// Option 3 (browser native)
// 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('')
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #js #generate #random #string #length
ADD COMMENT
Topic
Name
6+7 =