es.string.replace.js 5.4 KB

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