diff --git a/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts b/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts index 34648991ba35..894957609da4 100644 --- a/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts +++ b/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts @@ -438,6 +438,74 @@ Lorem Ipsum }); }); + it('preserves trailing hash in h1 title when not preceded by whitespace (e.g. C#)', () => { + const markdown = dedent` + + # Learn C# + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdown)).toEqual({ + content: markdown, + contentTitle: 'Learn C#', + }); + }); + + it('preserves trailing hash in h1 title with custom heading id', () => { + const markdown = dedent` + + # Learn C# {#learn-csharp} + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdown)).toEqual({ + content: markdown, + contentTitle: 'Learn C#', + }); + }); + + it('removes atx closing # while preserving trailing hash in heading text', () => { + const markdown = dedent` + + # Learn C# # + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdown)).toEqual({ + content: markdown, + contentTitle: 'Learn C#', + }); + }); + + it('removes atx closing # and custom heading id regardless of ordering', () => { + const markdownWithClosingAfter = dedent` + + # Learn C# {#learn-csharp} # + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdownWithClosingAfter)).toEqual({ + content: markdownWithClosingAfter, + contentTitle: 'Learn C#', + }); + + const markdownWithClosingBefore = dedent` + + # Learn C# # {#learn-csharp} + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdownWithClosingBefore)).toEqual({ + content: markdownWithClosingBefore, + contentTitle: 'Learn C#', + }); + }); + it('parses markdown h1 title at the top followed by h2 title', () => { const markdown = dedent` diff --git a/packages/docusaurus-utils/src/markdownUtils.ts b/packages/docusaurus-utils/src/markdownUtils.ts index 76f824f33ebd..a2564ccd1e4b 100644 --- a/packages/docusaurus-utils/src/markdownUtils.ts +++ b/packages/docusaurus-utils/src/markdownUtils.ts @@ -334,7 +334,9 @@ export function parseMarkdownContentTitle( contentTitle: toTextContentTitle( regularTitleMatch .groups!.title!.trim() - .replace(/\s*(?:\{#*[\w-]+\}|#+)$/, ''), + .replace(/[ \t]+#+$/, '') + .replace(/\s*\{#*[\w-]+\}$/, '') + .replace(/[ \t]+#+$/, ''), ).trim(), }; }