くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

nanoidでランダムな文字列を生成する

IDやパスワードなど、ランダムな文字列を生成したいなと思ったので、
いろいろ調べてみたときの備忘録。

nanoidが便利そうだった(*´ω`*)
型定義もあるので、TypeScriptでも使いやすい

インストール

$ npm i nanoid

使い方

import { customAlphabet } from 'nanoid';

// 生成時に使う文字の種類
const charactors = "1234567890abcdef";
// 生成する文字の長さ
const length = 5;

const nanoid = customAlphabet(charactors, 10);
const random = nanoid(length);
console.log(random); //=> "f01a2"

以上!!

ai/nanoid: A tiny (130 bytes), secure, URL-friendly, unique string ID generator for JavaScript