UNPKG

1.04 kBJavaScriptView Raw
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 */
13export default function dedent(strings) {
14 var str = '';
15
16 for (var i = 0; i < strings.length; ++i) {
17 str += strings[i];
18
19 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
20 str += i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]; // interpolation
21 }
22 }
23
24 var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline
25 .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
26 // fixes indentation by removing leading spaces and tabs from each line
27
28 var indent = '';
29
30 for (var _i2 = 0; _i2 < trimmedStr.length; _i2++) {
31 var char = trimmedStr[_i2];
32
33 if (char !== ' ' && char !== '\t') {
34 break;
35 }
36
37 indent += char;
38 }
39
40 return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
41}