どうも、ちょげ(@chogetarou)です。
文字列(string)を空白ごとに分割する方法を紹介します。
方法
文字列(string)を空白ごとに分割するには、split()とfilter()を使います。
まず、文字列からsplit()を呼び出します。
split()の引数に「/(\s+)/
」を指定します。
次に、split()からfilter()を呼び出します。
filter()の引数に「e => e.trim().length > 0
」を指定します。
const result: string[] = text.split(/(\s+)/).filter( e => e.trim().length > 0);
上記のstr.split().filter()は、呼び出した文字列(string)を空白ごとに分割した配列(array)を返します。
使用例
const text: string = " AB C D E FGH "
const result: string[] = text.split(/(\s+)/).filter( e => e.trim().length > 0);
console.log(result)
出力:
[ 'A', 'BC', 'DEF', 'GH', 'IJK' ]
コメント