dedent.mjs 1.0 KB

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