[JavaScript] replace 另類用法

function replacer(str, p1, p2, offset, s){
  return str + " - " + p1 + " , " + p2;
var newString = "XXzzzz".replace(/(X*)(z*)/, replacer);
//newString to "XXzzzz - XX , zzzz"

var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
//This prints "Smith, John".

Possible nameSupplied value
strThe matched substring. (Corresponds to $& above.)
p1, p2, ...The nth parenthesized submatch string, provided the first argument to replace was a RegExp object. (Correspond to $1, $2, etc. above.)
offsetThe offset of the matched substring within the total string being examined. (For example, if the total string was "abcd", and the matched substring was "bc", then this argument will be 1.)
sThe total string being examined.

引用自: replace - MDC

0 回應: