javascript 文字列の最初の1文字だけを抽出する

javascript 文字列の最初の1文字だけを抽出する

javascriptで、文字列の最後の1文字だけを抽出するサンプルコードを掲載してます。「substring」を使用した方法以外に4つくらい抽出方法があります。それぞれを使用したパフォーマンスも計測してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 108.0.5359.125

最初の1文字だけを抽出

最初の1文字だけを抽出するには、以下の4つの方法があります。

const str = "abcde";

console.log( str.substr(0, 1) )

console.log( str.charAt(0) )

console.log( str.slice(0, 1) )

console.log( str.substring(0, 1) )

実行結果

パフォーマンスは、「charAt」が少し悪いくらいです。

実行回数:1000000回 関数名:substr   実行時間:1.80(ms)
実行回数:1000000回 関数名:charAt   実行時間:3.10(ms)
実行回数:1000000回 関数名:slice    実行時間:2.20(ms)
実行回数:1000000回 関数名:substring 実行時間:1.90(ms)

漢字の場合でも、同じように取得することが可能です。

const str = "漢字の場合";

console.log( str.substr(0, 1) )

console.log( str.charAt(0) )

console.log( str.slice(0, 1) )

console.log( str.substring(0, 1) )

実行結果

ただし、サロゲートペアのような、文字コードを16bitではなく32bitで表してる場合は、うまく動作しないので注意が必要です。

const str = "😇😈😉";

console.log( str.substr(0, 1) )

console.log( str.charAt(0) )

console.log( str.slice(0, 1) )

console.log( str.substring(0, 1) )

実行結果

サンプルコード

以下は、
「実行」ボタンをクリックした際に、フォームに入力されて文字列の最初の1文字だけ抽出して表示するサンプルコードとなります。

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

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  window.onload = () => {

    btn.onclick = () => { 
      foo.innerHTML = txt.value.substr(0,1)
    }

  }

</script>

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

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-emerald-500 text-lg mr-auto">実行結果</h1>

      <p id="foo" class="font-semibold text-lg mr-auto"></p>

      <input
        class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
        id="txt" type="txt">

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-emerald-500 text-emerald-700 font-semibold hover:text-white py-2 px-4 border border-emerald-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、取得されていることが確認できます。