UNPKG

2.68 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 getSubstitution = require('../internals/get-substitution');
7var wellKnownSymbol = require('../internals/well-known-symbol');
8var IS_PURE = require('../internals/is-pure');
9
10var REPLACE = wellKnownSymbol('replace');
11var RegExpPrototype = RegExp.prototype;
12var max = Math.max;
13
14var stringIndexOf = function (string, searchValue, fromIndex) {
15 if (fromIndex > string.length) return -1;
16 if (searchValue === '') return fromIndex;
17 return string.indexOf(searchValue, fromIndex);
18};
19
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;
26 var position = 0;
27 var endOfLastMatch = 0;
28 var result = '';
29 if (searchValue != null) {
30 IS_REG_EXP = isRegExp(searchValue);
31 if (IS_REG_EXP) {
32 flags = String(requireObjectCoercible('flags' in RegExpPrototype
33 ? searchValue.flags
34 : getRegExpFlags.call(searchValue)
35 ));
36 if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes');
37 }
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);
43 }
44 }
45 string = String(O);
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));
55 } else {
56 replacement = getSubstitution(searchString, string, position, [], undefined, replaceValue);
57 }
58 result += string.slice(endOfLastMatch, position) + replacement;
59 endOfLastMatch = position + searchLength;
60 position = stringIndexOf(string, searchString, position + advanceBy);
61 }
62 if (endOfLastMatch < string.length) {
63 result += string.slice(endOfLastMatch);
64 }
65 return result;
66 }
67});