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/1/2026
Yes, there is a slugifyWithCounter() helper function. It creates a stateful slugify instance that automatically appends numeric counters to handle duplicate slugs.
How it works
The function returns a callable object with two key capabilities:
Basic functionality: When you call the slugify instance multiple times with the same input, it automatically appends a counter suffix starting from -2:
import {slugifyWithCounter} from '@sindresorhus/slugify';
const slugify = slugifyWithCounter();
slugify('foo bar'); //=> 'foo-bar'
slugify('foo bar'); //=> 'foo-bar-2'
Counter tracking: The implementation uses a Map to track occurrences [index.js:L111-L130]. It stores the count for each unique slugified string (case-insensitive) and appends the counter when a duplicate is detected.
Reset capability: You can clear the counter history with .reset() [index.d.ts:L252]:
slugify.reset();
slugify('foo bar'); //=> 'foo-bar'
Use case
This is particularly useful for generating unique HTML id attributes in documents where you have multiple sections with identical names (like duplicate "Example" subsection headings). It ensures each anchor link targets the correct headline without collisions.
The function is exported alongside the default slugify function [index.js:L101-L130].
FOLLOW_UPS:
- What options can be passed to slugifyWithCounter?
- How does the counter handle case sensitivity?
- Can I customize the counter format or suffix?
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.