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/25/2026
Yes, there is a slugifyWithCounter helper function. It's designed to handle multiple occurrences of the same string by appending a counter suffix.
How it works
You call slugifyWithCounter() to create a new instance with an internal counter [index.d.ts:L255-L287]:
import {slugifyWithCounter} from '@sindresorhus/slugify';
const slugify = slugifyWithCounter();
slugify('foo bar');
//=> 'foo-bar'
slugify('foo bar');
//=> 'foo-bar-2'
The function tracks occurrences internally. The first call returns the base slug, and subsequent identical slugs get a numeric suffix appended (starting at -2 for the second occurrence) [index.js:L101-L130].
Reset capability
The counter instance has a reset() method to clear the occurrence map [index.d.ts:L255]:
slugify.reset();
slugify('foo bar');
//=> 'foo-bar'
Use case
The primary use case is generating unique HTML id's for anchors, such as when processing markdown headers where you might have multiple sections with identically-named subsections [index.d.ts:L276-L287].
FOLLOW_UPS:
- What custom replacement options are available?
- How does the decamelize option transform text?
- What languages does transliteration support?
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.