(JS)String.prototype.replace

JavaScript の String の組み込みメソッド replace について引数に function をとる場合の情報があまりなかったのでメモメモ... もともと参照したのはいつも見ている Mozilla のサイトです.

MDN - String.prototype.replace()

なんか異様に難しく書いてあってアレですが,コンソールに出力して確認するのが一番速いです.

var string,
    replacer;

string = 'aaabbbcccdddeeefff';

replacer = function( match, capture1, capture2, offset, source ) {
  console.log( 'match: '    + match );
  console.log( 'capture1: ' + capture1 );
  console.log( 'capture2: ' + capture2 );
  console.log( 'offset: '   + offset );
  console.log( 'source: '   + source );
  return '[after replace!!! ]';
};

string = string.replace( /(b+).+?(e+)/, replacer );

console.log( 'string: ' + string );
match: bbbcccdddeee
capture1: bbb
capture2: eee
offset: 3
source: aaabbbcccdddeeefff
string: aaa[after replace!!! ]fff

コールバックのパラメータの数が不定です.. 1番目のパラメータには,マッチした部分文字列が入る. 後ろから2番目(offset)のパラメータには,マッチした部分文字列の開始文字のインデックスが入る. 一番後ろ(source)のパラメータには,元の文字列が入る. パラメータが不定の部分は正規表現でキャプチャした文字列が入ります.(なぜ配列にしなかったのだろう?) return する文字列はマッチした文字列に置き換わると.