get-substitution.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var uncurryThis = require('../internals/function-uncurry-this');
  2. var toObject = require('../internals/to-object');
  3. var floor = Math.floor;
  4. var charAt = uncurryThis(''.charAt);
  5. var replace = uncurryThis(''.replace);
  6. var stringSlice = uncurryThis(''.slice);
  7. var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g;
  8. var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g;
  9. // `GetSubstitution` abstract operation
  10. // https://tc39.es/ecma262/#sec-getsubstitution
  11. module.exports = function (matched, str, position, captures, namedCaptures, replacement) {
  12. var tailPos = position + matched.length;
  13. var m = captures.length;
  14. var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
  15. if (namedCaptures !== undefined) {
  16. namedCaptures = toObject(namedCaptures);
  17. symbols = SUBSTITUTION_SYMBOLS;
  18. }
  19. return replace(replacement, symbols, function (match, ch) {
  20. var capture;
  21. switch (charAt(ch, 0)) {
  22. case '$': return '$';
  23. case '&': return matched;
  24. case '`': return stringSlice(str, 0, position);
  25. case "'": return stringSlice(str, tailPos);
  26. case '<':
  27. capture = namedCaptures[stringSlice(ch, 1, -1)];
  28. break;
  29. default: // \d\d?
  30. var n = +ch;
  31. if (n === 0) return match;
  32. if (n > m) {
  33. var f = floor(n / 10);
  34. if (f === 0) return match;
  35. if (f <= m) return captures[f - 1] === undefined ? charAt(ch, 1) : captures[f - 1] + charAt(ch, 1);
  36. return match;
  37. }
  38. capture = captures[n - 1];
  39. }
  40. return capture === undefined ? '' : capture;
  41. });
  42. };