Question
Is there a slugify-with-counter helper? How does it work?
About sindresorhus/slugify · 2 messages · last activity 6/15/2026
Is there a slugify-with-counter helper? How does it work?
Yes, there is a slugifyWithCounter helper function. It's a factory function that creates a slugify instance with built-in duplicate detection and automatic numbering.
When you call slugifyWithCounter(), it returns a function that:
-2, -3, etc. to make each instance uniqueHere's the basic pattern from [index.js:L111-L130]:
const countable = (string, options) => {
string = slugify(string, options);
if (!string) {
return '';
}
const stringLower = string.toLowerCase();
const numberless = occurrences.get(stringLower.replace(/(?:-\d+?)+?$/, '')) || 0;
const counter = occurrences.get(stringLower);
occurrences.set(stringLower, typeof counter === 'number' ? counter + 1 : 1);
const newCounter = occurrences.get(stringLower) || 2;
if (newCounter >= 2 || numberless > 2) {
string = `${string}-${newCounter}`;
}
From [readme.md:L251-L280]:
import {slugifyWithCounter} from '@sindresorhus/slugify';
const slugify = slugifyWithCounter();
slugify('foo bar'); //=> 'foo-bar'
slugify('foo bar'); //=> 'foo-bar-2'
slugify.reset(); // Clear the counter
slugify('foo bar'); //=> 'foo-bar' (starts over)
The .reset() method clears all tracked occurrences, allowing you to start counting from scratch again.
FOLLOW_UPS:
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.