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 wellKnownSymbol = require('../internals/well-known-symbol');
7 var IS_PURE = require('../internals/is-pure');
9 var REPLACE = wellKnownSymbol('replace');
10 var RegExpPrototype = RegExp.prototype;
12 // `String.prototype.replaceAll` method
13 // https://github.com/tc39/proposal-string-replace-all
14 $({ target: 'String', proto: true }, {
15 replaceAll: function replaceAll(searchValue, replaceValue) {
16 var O = requireObjectCoercible(this);
17 var IS_REG_EXP, flags, replacer, string, searchString, template, result, position, index;
18 if (searchValue != null) {
19 IS_REG_EXP = isRegExp(searchValue);
21 flags = String(requireObjectCoercible('flags' in RegExpPrototype
23 : getRegExpFlags.call(searchValue)
25 if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes');
27 replacer = searchValue[REPLACE];
28 if (replacer !== undefined) {
29 return replacer.call(searchValue, O, replaceValue);
30 } else if (IS_PURE && IS_REG_EXP) {
31 return String(O).replace(searchValue, replaceValue);
35 searchString = String(searchValue);
36 if (searchString === '') return replaceAll.call(string, /(?:)/g, replaceValue);
37 template = string.split(searchString);
38 if (typeof replaceValue !== 'function') {
39 return template.join(String(replaceValue));
42 position = result.length;
43 for (index = 1; index < template.length; index++) {
44 result += String(replaceValue(searchString, position, string));
45 position += searchString.length + template[index].length;
46 result += template[index];