2010-11-03

[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");
print(newstr);
//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

沒有留言:

張貼留言

你好!歡迎你在我的 Blog 上留下你寶貴的意見。