javascript 正規表現を使って「yyyy/mm/dd」形式の日付を「年月日」に変更する

javascript 正規表現を使って「yyyy/mm/dd」形式の日付を「年月日」に変更する

javascriptで、正規表現を使って、「yyyy/mm/dd」形式の日付を「年月日」に変更するサンプルコードを記述してます。

環境

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

正規表現

「match」メソッドに正規表現を用いると、「yyyy/mm/dd」形式の日付を「年月日」に変更することが可能です。

const day = "2022/01/11";

// (\d+) 数値を1桁以上を抽出
const result = day.match( /^(\d+)\/(\d+)\/(\d+)$/ );

console.log(
  result[0],result[1],result[2],result[3]
);

console.log(
  `${result[1]}年${result[2]}月${result[3]}日`
);

実行結果

区切り文字が「-」だった場合は、以下のようにします。

const day = "2022-01-11";

// (\d+) 数値を1桁以上を抽出
const result = day.match( /^(\d+)\-(\d+)\-(\d+)$/ );

console.log(
  result[0],result[1],result[2],result[3]
);

console.log(
  `${result[1]}年${result[2]}月${result[3]}日`
);

サンプルコード

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

※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+)\/(\d+)\/(\d+)$/);

    // 結果を表示
    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-teal-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-gray-500"
      id="year" type="text">

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

</body>

</html>

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