RepoPilot

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

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

Question

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

RepoPilot

Yes, there is a slugifyWithCounter() helper in this repository. Here's how it works:

Overview

slugifyWithCounter() returns a new instance of the slugify function that maintains a counter to handle multiple occurrences of the same string [index.js:L112-L140].

How It Works

The function creates a Map called occurrences that tracks how many times each slugified string has been seen. When you call the returned countable function:

  1. It slugifies the input string normally
  2. It checks if that slug has been seen before
  3. If it's a duplicate (or if there are 3+ total occurrences including variants), it appends a counter: -2, -3, etc.
  4. It stores the occurrence count in the map for future calls

The counter also includes a .reset() method that clears the internal map [index.js:L135-L137].

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'

Use Case

This is particularly useful for generating unique HTML id attributes in documents with repeated section names, ensuring anchor links target the correct headlines [index.d.ts:L269-L271].

FOLLOW_UPS:

  • What options can be passed to slugifyWithCounter calls?
  • How does the counter handle case sensitivity?
  • What happens to existing number suffixes 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.