debian-mirror-gitlab/core-js/modules/esnext.string.replace-all.js

49 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-09-25 13:30:05 +05:30
'use strict';
var $ = require('../internals/export');
var requireObjectCoercible = require('../internals/require-object-coercible');
var isRegExp = require('../internals/is-regexp');
var getRegExpFlags = require('../internals/regexp-flags');
var wellKnownSymbol = require('../internals/well-known-symbol');
var IS_PURE = require('../internals/is-pure');
2019-10-31 01:37:42 +05:30
var REPLACE = wellKnownSymbol('replace');
2019-09-25 13:30:05 +05:30
var RegExpPrototype = RegExp.prototype;
// `String.prototype.replaceAll` method
// https://github.com/tc39/proposal-string-replace-all
$({ target: 'String', proto: true }, {
replaceAll: function replaceAll(searchValue, replaceValue) {
var O = requireObjectCoercible(this);
2019-10-31 01:37:42 +05:30
var IS_REG_EXP, flags, replacer, string, searchString, template, result, index;
2019-09-25 13:30:05 +05:30
if (searchValue != null) {
2019-10-31 01:37:42 +05:30
IS_REG_EXP = isRegExp(searchValue);
if (IS_REG_EXP) {
flags = String(requireObjectCoercible('flags' in RegExpPrototype
? searchValue.flags
: getRegExpFlags.call(searchValue)
));
if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes');
}
replacer = searchValue[REPLACE];
2019-09-25 13:30:05 +05:30
if (replacer !== undefined) {
return replacer.call(searchValue, O, replaceValue);
2019-10-31 01:37:42 +05:30
} else if (IS_PURE && IS_REG_EXP) {
return String(O).replace(searchValue, replaceValue);
2019-09-25 13:30:05 +05:30
}
}
string = String(O);
searchString = String(searchValue);
2019-10-31 01:37:42 +05:30
if (searchString === '') return replaceAll.call(string, /(?:)/g, replaceValue);
2019-09-25 13:30:05 +05:30
template = string.split(searchString);
if (typeof replaceValue !== 'function') {
return template.join(String(replaceValue));
}
result = template[0];
for (index = 1; index < template.length; index++) {
result += String(replaceValue(searchString, index - 1, string));
result += template[index];
}
return result;
}
});