esnext.string.replace-all.js 1.9 KB

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