RepoPilot

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

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

Question

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

RepoPilot

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

Overview

slugifyWithCounter() returns a new instance of a slug function that tracks occurrences of slugified strings and appends a counter to duplicates. This is useful for generating unique IDs, especially in scenarios like creating anchor links for multiple sections with the same name.

Implementation

The function [index.js:L112-L140] maintains an internal Map called occurrences to track how many times each slug has been generated. When you call the returned 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 multiple duplicates), it appends a numeric counter (e.g., -2, -3)
  4. It stores the occurrence count for future calls

Basic 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'

Key Features

  • reset() method [index.js:L138]: Clears the internal occurrence map, allowing you to start fresh.
  • Options support: The countable function accepts the same options parameter as the regular slugify() function [index.d.ts:L220-L285].

This is particularly useful when generating unique HTML id attributes for document headings where multiple sections might have identically-named subsections.

FOLLOW_UPS:

  • What options can I pass to slugifyWithCounter?
  • How does the counter handle edge cases?
  • What's the difference from regular slugify?

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.