diff --git a/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts b/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts index 34648991ba35..b24f8185c651 100644 --- a/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts +++ b/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts @@ -438,6 +438,88 @@ Lorem Ipsum }); }); + it('preserves trailing # when not preceded by space (e.g. C# or F#)', () => { + const markdownC = dedent` + + # Learn C# + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdownC)).toEqual({ + content: markdownC, + contentTitle: 'Learn C#', + }); + + const markdownF = dedent` + + # Learn F# + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdownF)).toEqual({ + content: markdownF, + contentTitle: 'Learn F#', + }); + }); + + it('preserves trailing # in title with custom anchor id', () => { + const markdown = dedent` + + # Learn C# {#learn-csharp} + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdown)).toEqual({ + content: markdown, + contentTitle: 'Learn C#', + }); + }); + + it('preserves trailing # in title with closing # sequence', () => { + const markdown = dedent` + + # Learn C# # + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdown)).toEqual({ + content: markdown, + contentTitle: 'Learn C#', + }); + }); + + it('handles empty heading consisting only of closing hashes', () => { + const markdown = dedent` + + # ### + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdown)).toEqual({ + content: markdown, + contentTitle: '', + }); + }); + + it('preserves literal trailing hash when followed by custom heading id', () => { + const markdown = dedent` + + # Title # {#id} + + Lorem Ipsum + + `; + expect(parseMarkdownContentTitle(markdown)).toEqual({ + content: markdown, + contentTitle: 'Title #', + }); + }); + 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 3a82a52cbb6e..53719f820c4b 100644 --- a/packages/docusaurus-utils/src/markdownUtils.ts +++ b/packages/docusaurus-utils/src/markdownUtils.ts @@ -334,7 +334,8 @@ export function parseMarkdownContentTitle( contentTitle: toTextContentTitle( regularTitleMatch .groups!.title!.trim() - .replace(/\s*(?:\{#*[\w-]+\}|#+)$/, ''), + .replace(/(?:^|\s+)#+$/, '') + .replace(/\s*\{#*[\w-]+\}$/, ''), ).trim(), }; }