Is there a slugify-with-counter helper? How does it work?
Is there a slugify-with-counter helper? How does it work?
About sindresorhus/slugify · 2 messages · last activity 5/18/2026
Yes, there is a slugifyWithCounter() helper function. Here's how it works:
Overview
slugifyWithCounter() creates a stateful slugify function that automatically appends numeric counters to duplicate slugs. This is useful for generating unique HTML ids for anchors and headlines [index.d.ts:L251-L280].
Behavior
When you call the returned function multiple times with the same or similar input:
- First occurrence: Returns the slug as normal (e.g.,
'foo-bar') - Subsequent identical occurrences: Appends an incrementing counter (e.g.,
'foo-bar-2','foo-bar-3')
[index.js:L101-L130] shows the implementation:
- It maintains a
Mapof occurrences to track how many times each slug has been generated - It extracts the base slug (removing any trailing numbers) to determine if duplicates exist
- If a slug appears 2+ times or the base slug appears more than 2 times total, it appends the counter
Example
import {slugifyWithCounter} from '@sindresorhus/slugify';
const slugify = slugifyWithCounter();
slugify('foo bar');
//=> 'foo-bar'
slugify('foo bar');
//=> 'foo-bar-2'
slugify.reset();
slugify('foo bar');
//=> 'foo-bar'
The reset() method clears the internal counter state, allowing you to start fresh [index.d.ts:L276-L287].
Use Case
This is particularly useful for documents with repeated section titles—for example, if you have multiple "Example" subsections, each will get a unique ID for proper anchor linking.
FOLLOW_UPS:
- What options can be passed to slugifyWithCounter?
- How does the counter detect duplicate base slugs?
- Can you customize the counter format or separator?
Want to ask your own question?
Open chat for sindresorhus/slugify →Public Q&A. Generated by RepoPilot from the actual source of sindresorhus/slugify. AI answers can be incomplete or stale — verify before relying on them.