es.string.replace.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. 'use strict';
  2. var apply = require('../internals/function-apply');
  3. var call = require('../internals/function-call');
  4. var uncurryThis = require('../internals/function-uncurry-this');
  5. var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
  6. var fails = require('../internals/fails');
  7. var anObject = require('../internals/an-object');
  8. var isCallable = require('../internals/is-callable');
  9. var isNullOrUndefined = require('../internals/is-null-or-undefined');
  10. var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
  11. var toLength = require('../internals/to-length');
  12. var toString = require('../internals/to-string');
  13. var requireObjectCoercible = require('../internals/require-object-coercible');
  14. var advanceStringIndex = require('../internals/advance-string-index');
  15. var getMethod = require('../internals/get-method');
  16. var getSubstitution = require('../internals/get-substitution');
  17. var regExpExec = require('../internals/regexp-exec-abstract');
  18. var wellKnownSymbol = require('../internals/well-known-symbol');
  19. var REPLACE = wellKnownSymbol('replace');
  20. var max = Math.max;
  21. var min = Math.min;
  22. var concat = uncurryThis([].concat);
  23. var push = uncurryThis([].push);
  24. var stringIndexOf = uncurryThis(''.indexOf);
  25. var stringSlice = uncurryThis(''.slice);
  26. var maybeToString = function (it) {
  27. return it === undefined ? it : String(it);
  28. };
  29. // IE <= 11 replaces $0 with the whole match, as if it was $&
  30. // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0
  31. var REPLACE_KEEPS_$0 = (function () {
  32. // eslint-disable-next-line regexp/prefer-escape-replacement-dollar-char -- required for testing
  33. return 'a'.replace(/./, '$0') === '$0';
  34. })();
  35. // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string
  36. var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () {
  37. if (/./[REPLACE]) {
  38. return /./[REPLACE]('a', '$0') === '';
  39. }
  40. return false;
  41. })();
  42. var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
  43. var re = /./;
  44. re.exec = function () {
  45. var result = [];
  46. result.groups = { a: '7' };
  47. return result;
  48. };
  49. // eslint-disable-next-line regexp/no-useless-dollar-replacements -- false positive
  50. return ''.replace(re, '$<a>') !== '7';
  51. });
  52. // @@replace logic
  53. fixRegExpWellKnownSymbolLogic('replace', function (_, nativeReplace, maybeCallNative) {
  54. var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0';
  55. return [
  56. // `String.prototype.replace` method
  57. // https://tc39.es/ecma262/#sec-string.prototype.replace
  58. function replace(searchValue, replaceValue) {
  59. var O = requireObjectCoercible(this);
  60. var replacer = isNullOrUndefined(searchValue) ? undefined : getMethod(searchValue, REPLACE);
  61. return replacer
  62. ? call(replacer, searchValue, O, replaceValue)
  63. : call(nativeReplace, toString(O), searchValue, replaceValue);
  64. },
  65. // `RegExp.prototype[@@replace]` method
  66. // https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
  67. function (string, replaceValue) {
  68. var rx = anObject(this);
  69. var S = toString(string);
  70. if (
  71. typeof replaceValue == 'string' &&
  72. stringIndexOf(replaceValue, UNSAFE_SUBSTITUTE) === -1 &&
  73. stringIndexOf(replaceValue, '$<') === -1
  74. ) {
  75. var res = maybeCallNative(nativeReplace, rx, S, replaceValue);
  76. if (res.done) return res.value;
  77. }
  78. var functionalReplace = isCallable(replaceValue);
  79. if (!functionalReplace) replaceValue = toString(replaceValue);
  80. var global = rx.global;
  81. if (global) {
  82. var fullUnicode = rx.unicode;
  83. rx.lastIndex = 0;
  84. }
  85. var results = [];
  86. while (true) {
  87. var result = regExpExec(rx, S);
  88. if (result === null) break;
  89. push(results, result);
  90. if (!global) break;
  91. var matchStr = toString(result[0]);
  92. if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
  93. }
  94. var accumulatedResult = '';
  95. var nextSourcePosition = 0;
  96. for (var i = 0; i < results.length; i++) {
  97. result = results[i];
  98. var matched = toString(result[0]);
  99. var position = max(min(toIntegerOrInfinity(result.index), S.length), 0);
  100. var captures = [];
  101. // NOTE: This is equivalent to
  102. // captures = result.slice(1).map(maybeToString)
  103. // but for some reason `nativeSlice.call(result, 1, result.length)` (called in
  104. // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
  105. // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
  106. for (var j = 1; j < result.length; j++) push(captures, maybeToString(result[j]));
  107. var namedCaptures = result.groups;
  108. if (functionalReplace) {
  109. var replacerArgs = concat([matched], captures, position, S);
  110. if (namedCaptures !== undefined) push(replacerArgs, namedCaptures);
  111. var replacement = toString(apply(replaceValue, undefined, replacerArgs));
  112. } else {
  113. replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
  114. }
  115. if (position >= nextSourcePosition) {
  116. accumulatedResult += stringSlice(S, nextSourcePosition, position) + replacement;
  117. nextSourcePosition = position + matched.length;
  118. }
  119. }
  120. return accumulatedResult + stringSlice(S, nextSourcePosition);
  121. }
  122. ];
  123. }, !REPLACE_SUPPORTS_NAMED_GROUPS || !REPLACE_KEEPS_$0 || REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE);