1
2

More than 1 year has passed since last update.

【Javascript】splitの結果に区切り文字を含める方法とその理由

Posted at

やりたいこと

'abc_def'.split('_') = ['abc', '_', 'def'];  // 実際は['abc', 'def']

例によってStackoverflowに答えがあり引数に区切り文字を()で囲んだ正規表現リテラルを渡せばよかった。

'abc_def'.split(/(_)/g);

Screen Shot 2022-04-28 at 21.42.45.png

なぜこうなるのか

自分の正規表現知識が足りないだけかと思ったがMDNにも書かれているECMAScriptの仕様だった。

If separator is a regular expression with capturing parentheses, then each time separator matches, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

つまりは()内にマッチした部分も結果に含められるようになる。
なのでちょっとしたパースもできる。覚えておくと役に立ちそう。

'<div>abc<span>def</span></div>'.split(/(<\/?[a-z]+>)/g)
  = ['', '<div>', 'abc', '<span>', 'def', '</span>', '', '</div>', '']
1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2