[JavaScript]文字列を1文字ずつに分割するには?

JavaScript

どうも、ちょげ(@chogetarou)です。

文字列を1文字ずつに分割する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

文字列を1文字ずつに分割する方法は、4つあります。

split()

1つ目は、split()を使う方法です。

まず、文字列からsplit()を呼び出します。

そして、split()の引数に空文字(”)を指定します。

const result = text.split('');

上記のsplit()は、呼び出した文字列を1文字ずつに分割した配列を返します。

使用例

const text = "Hello,World";

const result = text.split('');

console.log(result);
出力:
[
  'H', 'e', 'l', 'l',
  'o', ',', 'W', 'o',
  'r', 'l', 'd'
]

split() + 正規表現

2つ目は、split()と正規表現を使う方法です。

まず、文字列からsplit()を呼び出します。

そして、split()の引数に「/(?!$)/u」を指定します。

const result = text.split(/(?!$)/u);

上記のsplit()は、呼び出した文字列を1文字ずつに分割した配列を返します。

使用例

const text = "Hello,World";

const result = text.split(/(?!$)/u);

console.log(result);
出力:
[
  'H', 'e', 'l', 'l',
  'o', ',', 'W', 'o',
  'r', 'l', 'd'
]

スプレッド構文

3つ目は、スプレッド構文を使う方法です。

まず、[]を記述します。

そして、[]内に...と配列名を記述します。

const result = [...text];

上記の[]は、...の右辺の文字列を1文字ずつに分割した配列を生成します。

使用例

const text = "Hello,World";

const result = [...text];

console.log(result);
出力:
[
  'H', 'e', 'l', 'l',
  'o', ',', 'W', 'o',
  'r', 'l', 'd'
]

Array.from()

4つ目は、Array.from()を使う方法です。

まず、Array.from()を呼び出します。

そして、Array.from()の引数に文字列を指定します。

const result = Array.from(text);

上記のArray.from()は、引数に指定した文字列を1文字ずつに分割した配列を生成します。

使用例

const text = "Hello,World";

const result = Array.from(text);

console.log(result);
出力:
[
  'H', 'e', 'l', 'l',
  'o', ',', 'W', 'o',
  'r', 'l', 'd'
]
スポンサーリンク

まとめ

文字列(string)を1文字ずつに分割する方法は、次の4つです。

  • split()を使う方法
    const result = text.split('');
  • split()と正規表現を使う方法
    const result = text.split(/(?!$)/u);
  • スプレッド構文を使う方法
    const result = [...text];
  • Array.from()を使う方法
    const result = Array.from(text);

コメント

タイトルとURLをコピーしました