es.string.replace-all.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 getSubstitution = require('../internals/get-substitution');
  7. var wellKnownSymbol = require('../internals/well-known-symbol');
  8. var IS_PURE = require('../internals/is-pure');
  9. var REPLACE = wellKnownSymbol('replace');
  10. var RegExpPrototype = RegExp.prototype;
  11. var max = Math.max;
  12. var stringIndexOf = function (string, searchValue, fromIndex) {
  13. if (fromIndex > string.length) return -1;
  14. if (searchValue === '') return fromIndex;
  15. return string.indexOf(searchValue, fromIndex);
  16. };
  17. // `String.prototype.replaceAll` method
  18. // https://tc39.es/ecma262/#sec-string.prototype.replaceall
  19. $({ target: 'String', proto: true }, {
  20. replaceAll: function replaceAll(searchValue, replaceValue) {
  21. var O = requireObjectCoercible(this);
  22. var IS_REG_EXP, flags, replacer, string, searchString, functionalReplace, searchLength, advanceBy, replacement;
  23. var position = 0;
  24. var endOfLastMatch = 0;
  25. var result = '';
  26. if (searchValue != null) {
  27. IS_REG_EXP = isRegExp(searchValue);
  28. if (IS_REG_EXP) {
  29. flags = String(requireObjectCoercible('flags' in RegExpPrototype
  30. ? searchValue.flags
  31. : getRegExpFlags.call(searchValue)
  32. ));
  33. if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes');
  34. }
  35. replacer = searchValue[REPLACE];
  36. if (replacer !== undefined) {
  37. return replacer.call(searchValue, O, replaceValue);
  38. } else if (IS_PURE && IS_REG_EXP) {
  39. return String(O).replace(searchValue, replaceValue);
  40. }
  41. }
  42. string = String(O);
  43. searchString = String(searchValue);
  44. functionalReplace = typeof replaceValue === 'function';
  45. if (!functionalReplace) replaceValue = String(replaceValue);
  46. searchLength = searchString.length;
  47. advanceBy = max(1, searchLength);
  48. position = stringIndexOf(string, searchString, 0);
  49. while (position !== -1) {
  50. if (functionalReplace) {
  51. replacement = String(replaceValue(searchString, position, string));
  52. } else {
  53. replacement = getSubstitution(searchString, string, position, [], undefined, replaceValue);
  54. }
  55. result += string.slice(endOfLastMatch, position) + replacement;
  56. endOfLastMatch = position + searchLength;
  57. position = stringIndexOf(string, searchString, position + advanceBy);
  58. }
  59. if (endOfLastMatch < string.length) {
  60. result += string.slice(endOfLastMatch);
  61. }
  62. return result;
  63. }
  64. });