javascript 正規表現で「yyyymmdd」形式の日付を「年」と「月」と「日」に分ける

javascript 正規表現で「yyyymmdd」形式の日付を「年」と「月」と「日」に分ける

javascriptで、正規表現を用いて、「yyyymmdd」形式の日付を「年」と「月」と「日」に分けるサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

正規表現

「match」メソッドに正規表現を用いると、「yyyymmdd」形式の日付を「年」と「月」と「日」に配列をとして分けることが可能です。

let day = "20200117";

// (\d{4}) 4桁の数字を抽出 (\d{2}) 2桁の数字を抽出
result = day.match( /(\d{4})(\d{2})(\d{2})/ );

console.log(
  result[0],result[1],result[2],result[3] // 20200117 2020 01 17
);

実行結果

サンプルコード

以下は、
「実行」ボタンをクリックすると、フォームから取得した「yyyymmdd」形式の値を正規表現を使って「年」と「月」と「日」に分けて表示する
サンプルコードとなります。

※cssには「tailwind」を使用してます。また、関数はアロー関数で記述してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {

    const arr = year.value.match(/(\d{4})(\d{2})(\d{2})/);

    // 結果を表示
    result.innerHTML = `${arr[1]}年${arr[2]}月${arr[3]}日`;

  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">
      <p id="result" class="bg-blue-500 text-white py-2 px-4 rounded-full mt-4">結果</p>
    </div>

    <input
      class="mt-5 bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
      id="year" type="text">

    <div class="flex justify-center">
      <button id="btn" type="button"
        class="mt-5 bg-transparent border border-gray-500 hover:border-indigo-500 text-gray-500 hover:text-indigo-500 font-bold py-2 px-4 rounded-full">
        実行
      </button>
    </div>
  </div>

</body>

</html>

分けられていることが確認できます。