javascript 1文字単位で文字列を配列化する

javascript 1文字単位で文字列を配列化する

javascriptで、1文字単位で文字列を配列化するサンプルコードを掲載してます。「split」の引数を空文字にすることで可能です。文字列をそのまま配列化しても可能ですがパフォーマンスは悪いです。ブラウザはchromeを使用しています。

環境

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

1文字単位で文字列を配列化

1文字単位で文字列を配列化するは、「split」を使用します。

配列.split('')

実際に実行してます。

console.log( 'abcde'.split('') );
// ['a', 'b', 'c', 'd', 'e']

console.log( 'あいうえお'.split('') );
// ['あ', 'い', 'う', 'え', 'お']

また、パフォーマンスは悪くなりますが以下の方法でも可能です。

console.log( Array.from('abcde') );
// ['a', 'b', 'c', 'd', 'e']

console.log( [...'abcde'] );
// ['a', 'b', 'c', 'd', 'e']

サロゲートペア文字のような通常の2バイトで1文字で表すところを、4バイトで1文字となるものは、
「split」では、正しく分割されません。

console.log( '😘😫😭😮🙎'.split('') );
//  ['\uD83D', '\uDE18', '\uD83D', '\uDE2B', '\uD83D', '\uDE2D', '\uD83D', '\uDE2E', '\uD83D', '\uDE4E']

console.log( Array.from('😘😫😭😮🙎') );
// ['😘', '😫', '😭', '😮', '🙎']

console.log( [...'😘😫😭😮🙎'] );
// ['😘', '😫', '😭', '😮', '🙎']

サンプルコード

以下は、
「実行」ボタンをクリックした際に、ファーム入力されて文字列を配列化して表示するサンプルコードとなります。

※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 = () => {

      // フォームの値を配列から
      let arr = txt.value.split('')

      // 表示用の配列を用意
      let text = [];

      // 配列を利用してforEach文を作成
      arr.forEach((x, i) => text.push('<li>' + arr[i] + '</li>'))

      //innerHTMLを使用して表示    
      result.innerHTML = text.join('');
      
    }

  }

</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-sky-500 text-lg mr-auto">実行結果</h1>

      <ul id="result" class="list-disc">
      </ul>

      <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-sky-500 text-sky-700 font-semibold hover:text-white py-2 px-4 border border-sky-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、配列として表示されていることが確認できます。