Skip to content

Commit 72515d4

Browse files
authored
Create trim_indent.ts
1 parent 8682fae commit 72515d4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/format/trim_indent.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* this function strips the indent from the given text. It removes any leading whitespace characters
3+
* at the beginning of each line and trims any trailing newline characters. The function also
4+
* identifies the minimum indentation length among all lines and removes that amount of leading
5+
* whitespace from each line.
6+
* This is useful for cleaning up code or formatting text consistently.
7+
*
8+
* @example
9+
* ```ts
10+
* console.log(stripIndent(`
11+
* Hello
12+
* World!
13+
* `))
14+
* // Hello
15+
* // World!
16+
* ```
17+
*
18+
* @param text Text to trip
19+
* @returns The trimmed text.
20+
*/
21+
export default function stripIndent(text : string) {
22+
const formatted = text.trimEnd().replace(/^ *\n/gm, '');
23+
24+
const indentLength = formatted.match(/^ +/)?.[0].length;
25+
26+
return formatted.replace(new RegExp(`^ {${indentLength}}`, 'gm'), '')
27+
}

0 commit comments

Comments
 (0)