LoginSignup
14
9

More than 3 years have passed since last update.

Node.js: ランダムな文字列を生成する1行の関数

Last updated at Posted at 2020-03-13

Node.jsでランダムな文字列を生成する関数です。

36文字種

  • lengthで与えた長さの文字列を生成する。
  • 生成される文字列は/[0-9a-z]*/
  • このアルゴリズムにはバイアスがあり、0〜4が多めに出現するので、厳密なランダムではない。
const {randomBytes} = require('crypto')

function generateRandomString(length) {
  return randomBytes(length).reduce((p, i) => p + (i % 36).toString(36), '')
}

32文字種

  • lengthで与えた長さの文字列を生成する。
  • 生成される文字列は/[0-9a-v]*/
  • ランダムな0-256を32でモジュロ演算しているので、一応文字ごとの確率は均等なはず。
const {randomBytes} = require('crypto')

function generateRandomString(length) {
  return randomBytes(length).reduce((p, i) => p + (i % 32).toString(32), '')
}

Base32風の文字種

  • lengthで与えた長さの文字列を生成する。
  • 生成される文字種は32種類。
    • すべて大文字。
    • OやIと見た目が似てる0や1がない。
    • /[2-7A-Z]*/
  • ランダムな0-256を32でモジュロ演算しているので、一応文字ごとの確率は均等なはず。
const {randomBytes} = require('crypto')

const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split('')

function generateRandomString(length) {
  return randomBytes(length).reduce((p, i) => p + chars[(i % 32)], '')
}
14
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
9