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 6/29/2026
Yes, there is a slugifyWithCounter helper. It's a factory function that creates a slugify instance with built-in counting logic to handle duplicate slugs.
How it works
slugifyWithCounter() returns a callable function that tracks occurrences of slugified strings [index.js:L110-L130]. Here's the mechanism:
-
Creates a Map to track occurrences: Each time you call the slugify function, it stores how many times that slug (in lowercase) has been encountered.
-
Appends a counter suffix: If a slug has been seen before, it appends
-2,-3, etc. to make it unique. For example, callingslugify('foo bar')twice produces'foo-bar'and then'foo-bar-2'. -
Has a reset method: You can call
.reset()on the returned function to clear the occurrence map and start counting from scratch.
Example usage
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 primary use case is generating unique HTML id attributes for document sections or anchors [readme.md:L276-L305], ensuring that multiple similar headings (like multiple "Example" sections) don't collide.
FOLLOW_UPS:
- What are the default custom replacements?
- How does the decamelize option work?
- Can you disable lowercase conversion?
Want to ask your own question?
Open chat for sindresorhus/slugifyPublic Q&A. Generated by RepoPilot from the actual source of sindresorhus/slugify. AI answers can be incomplete or stale — verify before relying on them.