functional-replace-non-global.js (1473B)
1 // Copyright 2017 the V8 project authors. All rights reserved. 2 // This code is governed by the BSD license found in the LICENSE file. 3 4 /*--- 5 description: > 6 Function argument to String.prototype.replace gets groups as the last argument 7 esid: sec-regexp.prototype-@@replace 8 features: [regexp-named-groups] 9 info: | 10 RegExp.prototype [ @@replace ] ( string, replaceValue ) 11 14. Repeat, for each result in results, 12 j. Let namedCaptures be ? Get(result, "groups"). 13 k. If functionalReplace is true, then 14 iv. If namedCaptures is not undefined, 15 1. Append namedCaptures as the last element of replacerArgs. 16 ---*/ 17 18 let source = "(?<fst>.)(?<snd>.)"; 19 let alternateSource = "(?<fst>.)|(?<snd>.)"; 20 21 for (let flags of ["", "u"]) { 22 let i = 0; 23 let re = new RegExp(source, flags); 24 let result = "abcd".replace(re, 25 (match, fst, snd, offset, str, groups) => { 26 assert.sameValue(i++, 0); 27 assert.sameValue("ab", match); 28 assert.sameValue("a", groups.fst); 29 assert.sameValue("b", groups.snd); 30 assert.sameValue("a", fst); 31 assert.sameValue("b", snd); 32 assert.sameValue(0, offset); 33 assert.sameValue("abcd", str); 34 return `${groups.snd}${groups.fst}`; 35 }); 36 assert.sameValue("bacd", result); 37 assert.sameValue(i, 1); 38 39 let re2 = new RegExp(alternateSource, flags); 40 assert.sameValue("undefinedbcd", 41 "abcd".replace(re2, 42 (match, fst, snd, offset, str, groups) => groups.snd)); 43 } 44 45 reportCompare(0, 0);