UNPKG

1.89 kBJavaScriptView Raw
1'use strict';
2var $ = require('../internals/export');
3var requireObjectCoercible = require('../internals/require-object-coercible');
4var isRegExp = require('../internals/is-regexp');
5var getRegExpFlags = require('../internals/regexp-flags');
6var wellKnownSymbol = require('../internals/well-known-symbol');
7var IS_PURE = require('../internals/is-pure');
8
9var REPLACE = wellKnownSymbol('replace');
10var RegExpPrototype = RegExp.prototype;
11
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, index;
18 if (searchValue != null) {
19 IS_REG_EXP = isRegExp(searchValue);
20 if (IS_REG_EXP) {
21 flags = String(requireObjectCoercible('flags' in RegExpPrototype
22 ? searchValue.flags
23 : getRegExpFlags.call(searchValue)
24 ));
25 if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes');
26 }
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);
32 }
33 }
34 string = String(O);
35 searchString = String(searchValue);
36 if (searchString === '') return replaceAll.call(O, /(?:)/g, replaceValue);
37 template = string.split(searchString);
38 if (typeof replaceValue !== 'function') {
39 return template.join(String(replaceValue));
40 }
41 result = template[0];
42 for (index = 1; index < template.length; index++) {
43 result += String(replaceValue(searchString, index - 1, string));
44 result += template[index];
45 }
46 return result;
47 }
48});