replace.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.replaceAll = exports.replace = void 0;
  4. function replace(segments, pattern, ...replacers) {
  5. const str = toString(segments);
  6. const match = str.match(pattern);
  7. if (match && match.index !== undefined) {
  8. const start = match.index;
  9. const end = start + match[0].length;
  10. offsetStack();
  11. overwrite(segments, [start, end], ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));
  12. resetOffsetStack();
  13. }
  14. }
  15. exports.replace = replace;
  16. function replaceAll(segments, pattern, ...replacers) {
  17. const str = toString(segments);
  18. const allMatch = str.matchAll(pattern);
  19. let length = str.length;
  20. let lengthDiff = 0;
  21. for (const match of allMatch) {
  22. if (match.index !== undefined) {
  23. const start = match.index + lengthDiff;
  24. const end = start + match[0].length;
  25. offsetStack();
  26. overwrite(segments, [start, end], ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));
  27. resetOffsetStack();
  28. const newLength = getLength(segments);
  29. lengthDiff += newLength - length;
  30. length = newLength;
  31. }
  32. }
  33. }
  34. exports.replaceAll = replaceAll;
  35. //# sourceMappingURL=replace.js.map