RepoPilot

Is there a slugify-with-counter helper? How does it work?

About sindresorhus/slugify · 2 messages · last activity 6/15/2026

Question

Is there a slugify-with-counter helper? How does it work?

RepoPilot

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.

How it works

When you call slugifyWithCounter(), it returns a function that:

  1. Tracks occurrences: Each time you call the returned function with a string, it keeps count of how many times that slug has been used
  2. Appends counters: If the same slug appears more than once, it appends -2, -3, etc. to make each instance unique
  3. Handles existing numbers: It intelligently handles strings that already contain numbers in their slugs

Here'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}`;
    }

Example usage

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:

  • What are the main options you can pass to slugify?
  • How does decamelize option transform strings?
  • Can you preserve custom characters in slugs?

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.