Skip to content

Commit 874d40b

Browse files
authored
fix(valid-heading-anchor): collapse repeated spaces in normalized heading anchors (#24)
1 parent 3d65a62 commit 874d40b

3 files changed

Lines changed: 12 additions & 1 deletion

File tree

src/rules/valid-heading-anchor/index.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ const invalid: InvalidTestCase[] = [
6666
output: '# 中文标题 {#foo_bar123}',
6767
errors: [{ messageId: 'invalidHeadingAnchor' }],
6868
},
69+
{
70+
description: 'should collapse multiple spaces in anchor fix',
71+
code: '# 中文标题 {#Chinese Title}',
72+
output: '# 中文标题 {#chinese-title}',
73+
errors: [{ messageId: 'missingAnchor' }],
74+
},
6975
]
7076

7177
run({

src/utils/anchor.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export function hasChinese(str: string): boolean {
6161
*/
6262
export function normalizeAnchor(anchor: string): string {
6363
const lowerCaseAnchor = anchor.toLowerCase()
64-
const completeHyphen = lowerCaseAnchor.replace(/[\s.]/g, '-')
64+
const completeHyphen = lowerCaseAnchor.replace(/[\s.]+/g, '-')
6565
const keepLegalCharacters = completeHyphen.replace(/[^a-z0-9_-]/g, '')
6666
return keepLegalCharacters.replace(/^-+|-+$/g, '')
6767
}

tests/utils/anchor.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@ describe('normalizeAnchor', () => {
8585
expect(normalizeAnchor('中文-title')).toBe('title')
8686
})
8787

88+
it('should collapse repeated spaces into a single hyphen', () => {
89+
expect(normalizeAnchor('Your first test')).toBe('your-first-test')
90+
expect(normalizeAnchor('Your first test')).toBe('your-first-test')
91+
})
92+
8893
it('should preserve digits and hyphens', () => {
8994
expect(normalizeAnchor('intro-2')).toBe('intro-2')
9095
expect(normalizeAnchor('API-Reference_v2')).toBe('api-reference_v2')

0 commit comments

Comments
 (0)