get-substitution.js 1.4 KB

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