dedent.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = dedent;
  6. /**
  7. * An ES6 string tag that fixes indentation. Also removes leading newlines
  8. * and trailing spaces and tabs, but keeps trailing newlines.
  9. *
  10. * Example usage:
  11. * const str = dedent`
  12. * {
  13. * test
  14. * }
  15. * `;
  16. * str === "{\n test\n}\n";
  17. */
  18. function dedent(strings) {
  19. var str = '';
  20. for (var i = 0; i < strings.length; ++i) {
  21. str += strings[i];
  22. if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
  23. str += i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]; // interpolation
  24. }
  25. }
  26. var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline
  27. .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
  28. // fixes indentation by removing leading spaces and tabs from each line
  29. var indent = '';
  30. for (var _i2 = 0; _i2 < trimmedStr.length; _i2++) {
  31. var char = trimmedStr[_i2];
  32. if (char !== ' ' && char !== '\t') {
  33. break;
  34. }
  35. indent += char;
  36. }
  37. return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
  38. }