LoginSignup
15
7

More than 3 years have passed since last update.

重複しない任意長のランダム文字列を生成する方法

Posted at

TL;DR

高速で安全、手軽にランダム文字列を生成したいときはai/nanoidを使う。

特徴

README.mdより意訳しています。

使い方

デフォルトでは[a-zA-Z0-9_-]から21文字で生成されます。

import { nanoid } from 'nanoid'
nanoid() //=> "yVQk_rn0A60LXcOR-2voE"

非同期に生成する

import { nanoid } from 'nanoid/async'
async function createUser () {
  user.id = await nanoid()
}

任意の長さにする

短くするほど重複しやすくなるので注意してください。
重複しやすさを簡易計算できるサイトもあるので参考にしましょう。

nanoid(10) //=> "3juqViJh32"
nanoid(3)  //=> "eEh"

出現する文字を絞る

customAlphabetの引数に使いたい文字と文字長を指定すると、ランダム文字列生成関数が作れます。

import { customAlphabet } from 'nanoid'
const randomColor = customAlphabet('1234567890abcdef', 6)
font.color = `#${randomColor()}` //=> "#a1ea8e"

ちなみに、CyberAP/nanoid-dictionaryというパッケージを利用すれば、使いたい文字に指定できる頻出パターンが入っています。

  • numbers:0〜9の数字
  • lowercase:小文字の英字
  • uppercase:大文字の英字
  • nolookalikesa-zA-Z0-9から見間違いやすい1, l, I, 0, O, o, u, v, 5, S, sを取り除いたもの

記事執筆時点のバージョン

// $ cat node_modules/nanoid/package.json | jq '{ name, version }'
{
  "name": "nanoid",
  "version": "3.0.2"
}
15
7
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
15
7