📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Generate Hext String in JavaScript

You can use this to generate some uinque ID for your API token for example.

Basic Javascript with Math

function generateHexString(length) {
  var ret = "";
  while (ret.length < length) {
    ret += Math.random().toString(16).substring(2);
  }
  return ret.substring(0, length);
}

With crypto in Browser

function generateHexString(length) {
  var ret = "";
  var hex = "0123456789abcdef";
  var arr = new Uint8Array(Math.ceil(length/2));
  window.crypto.getRandomValues(arr);
  for (var i = 0; i < arr.length; i++) {
    ret += hex[arr[i] >> 4] + hex[arr[i] & 15];
  }
  return ret.slice(0, length);
}

Using Crypto in Node.js

const crypto = require("crypto");

function generateHexString(length) {
  return crypto.randomBytes(Math.ceil(length/2))
    .toString("hex") // convert to hexadecimal format
    .slice(0,length);   // return required number of characters
}

Usage:

generateHexString(40) // f69977ae2f12d631b19b601a4bc8642cbbcc10f3