1 | /**
|
2 | * Find each match of a regular expression in a string, apply a function to
|
3 | * each match and replace the matched string with the result of the function.
|
4 | *
|
5 | * @param {String} str
|
6 | * @param {RegExp} re
|
7 | * @param {Function} fn
|
8 | * @param {String} newstr
|
9 | * @api public
|
10 | */
|
11 |
|
12 | exports.gsub = function (str, re, fn, /*optional*/newstr) {
|
13 | newstr = newstr || '';
|
14 | var match = re.exec(str);
|
15 | if (match) {
|
16 | newstr += str.slice(0, match.index);
|
17 | newstr += fn.apply(null, match);
|
18 | remaining = str.slice(match.index + match[0].length);
|
19 | return exports.gsub(remaining, re, fn, newstr);
|
20 | }
|
21 | return newstr + str;
|
22 | };
|