どうも、ちょげ(@chogetarou)です。
文字列(string)を空白ごとに分割する方法を紹介します。
方法

文字列(string)を空白ごとに分割するには、split()とfilter()を使います。
まず、文字列からsplit()を呼び出します。
split()の引数に「/(\s+)/
」を指定します。
次に、split()からfilter()を呼び出します。
filter()の引数に「e => e.trim().length > 0
」を指定します。
const result = text.split(/(\s+)/).filter( e => e.trim().length > 0);
上記のsplit().filter()は、呼び出した文字列を空白ごとに分割したオブジェクトを返します。
使用例
const text = "A BC DEF GH IJK";
const result = text.split(/(\s+)/).filter( e => e.trim().length > 0);
console.log(result);
出力:
[ 'A', 'BC', 'DEF', 'GH', 'IJK' ]
コメント