2 var $ = require('../internals/export');
3 var requireObjectCoercible = require('../internals/require-object-coercible');
4 var isRegExp = require('../internals/is-regexp');
5 var getRegExpFlags = require('../internals/regexp-flags');
6 var getSubstitution = require('../internals/get-substitution');
7 var wellKnownSymbol = require('../internals/well-known-symbol');
8 var IS_PURE = require('../internals/is-pure');
10 var REPLACE = wellKnownSymbol('replace');
11 var RegExpPrototype = RegExp.prototype;
14 var stringIndexOf = function (string, searchValue, fromIndex) {
15 if (fromIndex > string.length) return -1;
16 if (searchValue === '') return fromIndex;
17 return string.indexOf(searchValue, fromIndex);
20 // `String.prototype.replaceAll` method
21 // https://tc39.es/ecma262/#sec-string.prototype.replaceall
22 $({ target: 'String', proto: true }, {
23 replaceAll: function replaceAll(searchValue, replaceValue) {
24 var O = requireObjectCoercible(this);
25 var IS_REG_EXP, flags, replacer, string, searchString, functionalReplace, searchLength, advanceBy, replacement;
27 var endOfLastMatch = 0;
29 if (searchValue != null) {
30 IS_REG_EXP = isRegExp(searchValue);
32 flags = String(requireObjectCoercible('flags' in RegExpPrototype
34 : getRegExpFlags.call(searchValue)
36 if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes');
38 replacer = searchValue[REPLACE];
39 if (replacer !== undefined) {
40 return replacer.call(searchValue, O, replaceValue);
41 } else if (IS_PURE && IS_REG_EXP) {
42 return String(O).replace(searchValue, replaceValue);
46 searchString = String(searchValue);
47 functionalReplace = typeof replaceValue === 'function';
48 if (!functionalReplace) replaceValue = String(replaceValue);
49 searchLength = searchString.length;
50 advanceBy = max(1, searchLength);
51 position = stringIndexOf(string, searchString, 0);
52 while (position !== -1) {
53 if (functionalReplace) {
54 replacement = String(replaceValue(searchString, position, string));
56 replacement = getSubstitution(searchString, string, position, [], undefined, replaceValue);
58 result += string.slice(endOfLastMatch, position) + replacement;
59 endOfLastMatch = position + searchLength;
60 position = stringIndexOf(string, searchString, position + advanceBy);
62 if (endOfLastMatch < string.length) {
63 result += string.slice(endOfLastMatch);