ランダムパスワードをReactで生成する

2025/07/01

以下のコードでは、10文字のパスワードを生成する。
パスワードには、 アルファベット小文字, アルファベット大文字, 数字, 記号をそれぞれ1つ以上含む。それ以外の6文字はランダムに含まれる。

export const passwordGenerator = () => {
  const apl = 'abcdefghijklmnopqrstuvwxyz';
  const num = '0123456789';
  const sym = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
  const all = apl + apl.toUpperCase() + num + sym;
  const getRandomChar = (chars: string) => chars[Math.floor(Math.random() * chars.length)];

  const autoGeneratedPassword = [
    getRandomChar(apl),
    getRandomChar(apl.toUpperCase()),
    getRandomChar(num),
    getRandomChar(sym)
  ];

  while (autoGeneratedPassword.length < 10) {
    autoGeneratedPassword.push(getRandomChar(all));
  }

  for (let i = autoGeneratedPassword.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [autoGeneratedPassword[i], autoGeneratedPassword[j]] = [autoGeneratedPassword[j], autoGeneratedPassword[i]];
  }

  return autoGeneratedPassword.join('');
};