[JavaScript]文字列を文字数で分割するには?

JavaScript

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

文字列(string)を文字数で分割する方法を紹介します。

スポンサーリンク

方法

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

文字列(string)を文字数で分割するには、match()を使います。

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

そして、match()の引数に、/.{1,文字数}/gを指定します。

//n=文字数
const result = text.match(/.{1,n}/g);

上記のmatch()は、呼び出した文字列を特定の文字数で分割したオブジェクトを返します。

使用例

const text = "Hello,World";
const text2 = "ABCDEFGHIJKL";

const result = text.match(/.{1,2}/g);
const result2 = text2.match(/.{1,4}/g);

console.log(result);
console.log(result2);
出力:
[ 'He', 'll', 'o,', 'Wo', 'rl', 'd' ]
[ 'ABCD', 'EFGH', 'IJKL' ]

コメント

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