diff --git a/text/unstable_dedent.ts b/text/unstable_dedent.ts index 7d09673d670b..5262826c4720 100644 --- a/text/unstable_dedent.ts +++ b/text/unstable_dedent.ts @@ -16,7 +16,7 @@ const WHITE_SPACE_ONLY_LINE_REGEXP = new RegExp( * Removes indentation from multiline strings. * * - Removes leading newline - * - Removes trailing whitespace, including newlines + * - Removes a single trailing newline (with any preceding whitespace on that line) * - Replaces whitespace-only lines with empty lines * - Finds the minimum indentation among remaining lines and removes that much indentation from all of them * @@ -44,7 +44,7 @@ export function dedent(input: string): string; * Removes indentation from multiline strings. * * - Removes leading newline - * - Removes trailing whitespace, including newlines + * - Removes a single trailing newline (with any preceding whitespace on that line) * - Replaces whitespace-only lines with empty lines * - Finds the minimum indentation among remaining lines and removes that much indentation from all of them * @@ -76,7 +76,10 @@ export function dedent( // Substitute nonempty placeholder so multiline substitutions do not affect indent width. const joinedTemplate = typeof input === "string" ? input : input.join("x"); const ignoreFirstUnindented = !joinedTemplate.startsWith("\n"); - const trimmedTemplate = joinedTemplate.replace(/^\n/, "").trimEnd(); + const trimmedTemplate = joinedTemplate.replace(/^\n/, "").replace( + /\n[\t ]*$/, + "", + ); const lines = trimmedTemplate.split("\n"); const linesToCheck = lines.slice( @@ -90,7 +93,7 @@ export function dedent( const inputString = typeof input === "string" ? input : String.raw({ raw: input }, ...values); - const trimmedInput = inputString.replace(/^\n/, "").trimEnd(); + const trimmedInput = inputString.replace(/^\n/, "").replace(/\n[\t ]*$/, ""); // No lines to indent if (!indent) return trimmedInput; diff --git a/text/unstable_dedent_test.ts b/text/unstable_dedent_test.ts index 54274971137a..8d8f716be1a7 100644 --- a/text/unstable_dedent_test.ts +++ b/text/unstable_dedent_test.ts @@ -22,6 +22,15 @@ Deno.test("dedent() handles example 2", () => { ); }); +// Test case for issue #6831 +Deno.test("dedent() only strips single trailing newline", () => { + const result = dedent` + a + + `; + assertEquals(result, "a\n"); +}); + Deno.test("dedent() handles empty lines", () => { assertEquals( dedent(`