@lpm.dev/neo.slug

Pool

slug

Modern URL slug generation library - Unicode transliteration, customizable options, unique slugs. Zero dependencies, TypeScript-first, tree-shakeable. Modernizes the slugify ecosystem.

install @lpm.dev/neo.slug

@lpm.dev/neo.slug

Modern, fast, and lightweight URL slug generation for JavaScript

Why neo.slug?

  • Fast: The package processes more than 100,000 short strings per second in the included benchmark.
  • Small: Subpath imports keep unused features out of compatible bundles.
  • Tree-shakeable: Import only the functions that you use.
  • TypeScript-first: The package includes declaration files and uses strict mode.
  • Latin-script support: The package handles common European diacritics and selected symbols.
  • Safe defaults: The package creates ASCII URL path segments by default.
  • Zero dependencies: The package has no external runtime dependencies.

Performance

Benchmark results depend on the runtime, hardware, options, and input text. See BENCHMARKS.md for the current method and results.

Installation

lpm install @lpm.dev/neo.slug

Quick Start

import { slug } from "@lpm.dev/neo.slug";

// Basic usage
slug("Hello World"); // 'hello-world'
slug("Café München"); // 'cafe-munchen'
slug("I ♥ JavaScript"); // 'i-love-javascript'

// camelCase conversion
slug("fooBarBaz"); // 'foo-bar-baz'
slug("ES6, ES7, ES8"); // 'es-6-es-7-es-8'

// Custom options
slug("Hello World", { separator: "_" }); // 'hello_world'
slug("Hello World", { lowercase: false }); // 'Hello-World'
slug("Hello@World.com", { strict: true }); // 'helloworld-com'

API

slug(input, options?)

Convert a string to a URL-safe slug.

Parameters:

  • input (string): String to slugify
  • options (object, optional): Configuration options

Options:

  • separator (string): Empty, -, ., _, or ~ (default: '-')
  • lowercase (boolean): Convert to lowercase (default: true)
  • strict (boolean): Remove built-in semantic symbols unless explicitly replaced (default: false)
  • trim (boolean): Trim leading/trailing separators (default: true)
  • locale (string): Locale for lowercase conversion (default: runtime locale)
  • preserve (string[]): URL-safe characters to preserve: -, ., _, or ~
  • remove (RegExp): Pattern whose matches become word boundaries
  • replacements (Record<string, string>): Atomic, literal character replacements
  • custom (function): Custom transliteration function

Returns: URL-safe slug string

Examples:

// Separator
slug("Hello World", { separator: "_" }); // 'hello_world'
slug("foo bar baz", { separator: "." }); // 'foo.bar.baz'
slug("Hello World", { separator: "" }); // 'helloworld'

// Lowercase
slug("Hello World", { lowercase: false }); // 'Hello-World'

// Strict mode (remove all non-alphanumeric except separator)
slug("Hello@World.com", { strict: true }); // 'helloworld-com'
slug("foo#bar$baz", { strict: true }); // 'foobarbaz'

// Trim
slug("-hello world-", { trim: false }); // '-hello-world-'

// Preserve characters
slug("hello.world", { preserve: ["."] }); // 'hello.world'
slug("user_name_123", { preserve: ["_"] }); // 'user_name_123'

// Remove specific characters
slug("Hello*World", { remove: /[*]/g }); // 'hello-world'

// Custom replacements
slug("foo & bar", { replacements: { "&": "n" } }); // 'foo-n-bar'

// Custom transliteration
const digitNames = ["zero", "one", "two", "three"];
slug("foo123", {
  custom: (str) => str.replace(/\d/g, (n) => digitNames[Number(n)] ?? ""),
}); // 'fooonetwothree'

Advanced Features

createSlugger(defaultOptions)

Create a reusable slugger function with preset options.

import { createSlugger } from "@lpm.dev/neo.slug";

const blogSlugger = createSlugger({
  separator: "-",
  lowercase: true,
  strict: true,
});

blogSlugger("Hello World"); // 'hello-world'
blogSlugger("Café München"); // 'cafe-munchen'

// Override options per call
blogSlugger("Hello World", { lowercase: false }); // 'Hello-World'

uniqueSlug(input, checker, options?)

Find an available slug candidate with automatic suffix checks.

import { uniqueSlug } from "@lpm.dev/neo.slug";

// With a Set
const reserved = new Set(["hello-world"]);
await uniqueSlug("Hello World", reserved); // 'hello-world-2'
reserved.has("hello-world-2"); // true

// With a function (e.g., database check)
const signal = AbortSignal.timeout(2_000);
const checkDatabase = async (slug: string, signal?: AbortSignal) => {
  return Boolean(await db.posts.findOne({ slug, signal }));
};
await uniqueSlug("My Post", checkDatabase, {
  maxAttempts: 25,
  signal,
}); // 'my-post' or 'my-post-2'

// Synchronous version
import { uniqueSlugSync } from "@lpm.dev/neo.slug";
const reservedTests = new Set(["test"]);
uniqueSlugSync("Test", reservedTests); // 'test-2'
reservedTests.has("test-2"); // true

A Set checker reserves the returned candidate in the Set. The reservation occurs without an await gap.

A function checker does not reserve the candidate. Use a database unique constraint and retry after a constraint conflict.

The default limit is 100 checks. Set maxAttempts to an integer from 1 through 1,000.

Use signal to cancel the operation. The checker receives the same signal and must cancel its own database request.

The functions throw an error when the input produces an empty slug.

Unicode Support

neo.slug transliterates supported Latin-script characters to ASCII. It uses this approach:

  • NFD normalization for diacritics (é → e, ñ → n, ü → u, ö → o, ä → a)
  • Custom maps for characters that NFD does not handle:
    • Germanic: ß → ss
    • Nordic: å → aa, ø → o, æ → ae
    • Polish: ł → l, ą → a, ć → c, ę → e, ń → n, ó → o
    • Polish: ś → s, ź → z, ż → z
    • Czech: č → c, ď → d, ě → e, ň → n, ř → r
    • Czech: š → s, ť → t, ů → u, ž → z
    • Turkish: ı → i, ğ → g, ş → s
    • Romanian: ă → a, â → a, î → i, ș → s, ț → t
    • Vietnamese: đ → d

Examples:

slug("München"); // 'munchen'
slug("Zürich"); // 'zurich'
slug("Malmö"); // 'malmo'
slug("Łódź"); // 'lodz'
slug("Kraków"); // 'krakow'
slug("Café"); // 'cafe'

The built-in map does not transliterate Greek, Cyrillic, Arabic, or CJK scripts. Unsupported text can produce an empty slug.

Use custom to add a transliterator for unsupported scripts:

slug("Hello 世界", {
  custom: (input) => input.replace(/世界/g, "world"),
}); // 'hello-world'

Real-World Use Cases

Blog Post URLs

const blogSlugger = createSlugger({ strict: true });

blogSlugger("10 Ways to Improve Your JavaScript Skills");
// '10-ways-to-improve-your-javascript-skills'

blogSlugger("React vs Vue vs Angular: Which One to Choose?");
// 'react-vs-vue-vs-angular-which-one-to-choose'

Product URLs

slug('MacBook Pro 14" (2024)'); // 'macbook-pro-14-2024'
slug("iPhone 15 Pro Max - 256GB"); // 'iphone-15-pro-max-256-gb'
slug("Sony WH-1000XM5 Wireless Headphones"); // 'sony-wh-1000-xm-5-wireless-headphones'

User Profiles

const usernameSlugger = createSlugger({
  separator: "-",
  lowercase: true,
  strict: true,
});

// Find an available profile slug candidate
const username = await uniqueSlug("John Smith", (slug) =>
  db.users.exists({ username: slug }),
);
// 'john-smith' or 'john-smith-2', 'john-smith-3', etc.

Tree-Shaking

Import only what you need for optimal bundle size:

// Import the core function
import { slug } from "@lpm.dev/neo.slug/slug";

// Import core and advanced features
import { slug, createSlugger, uniqueSlug } from "@lpm.dev/neo.slug";

// Or use subpath imports for maximum tree-shaking
import { slug } from "@lpm.dev/neo.slug/slug";
import { createSlugger } from "@lpm.dev/neo.slug/advanced";

Migration Guides

From slugify

neo.slug is mostly compatible with slugify:

// Before (slugify)
import slugify from "slugify";
slugify("Hello World"); // 'Hello-World'
slugify("Hello World", { lower: true }); // 'hello-world'
slugify("Hello World", { replacement: "_" }); // 'Hello_World'
slugify("Hello World", { strict: true }); // 'Hello-World'

// After (neo.slug)
import { slug } from "@lpm.dev/neo.slug";
slug("Hello World"); // 'hello-world' (lowercase by default!)
slug("Hello World", { lowercase: false }); // 'Hello-World'
slug("Hello World", { separator: "_" }); // 'hello_world'
slug("Hello World", { strict: true }); // 'hello-world'

Key differences:

  • neo.slug lowercases by default (set lowercase: false to match slugify)
  • Option name: replacement → separator
  • Option name: lower → lowercase

From @sindresorhus/slugify

neo.slug matches common @sindresorhus/slugify results for supported Latin-script input:

// Before (@sindresorhus/slugify)
import slugify from "@sindresorhus/slugify";
slugify("Hello World"); // 'hello-world'
slugify("I ♥ Dogs"); // 'i-love-dogs'
slugify("Café"); // 'cafe'

// After (neo.slug)
import { slug } from "@lpm.dev/neo.slug";
slug("Hello World"); // 'hello-world' ✓
slug("I ♥ Dogs"); // 'i-love-dogs' ✓
slug("Café"); // 'cafe' ✓

Differences:

  • neo.slug supports a smaller transliteration set.
  • neo.slug rejects separators that are unsafe in one URL path segment.
  • neo.slug adds createSlugger, uniqueSlug, and uniqueSlugSync.

Bundle Size Comparison

Package Min + Gzip Tree-shakeable
@lpm.dev/neo.slug See current build ✅ Yes
slugify ~3.5 KB ❌ No
@sindresorhus/slugify ~7 KB ❌ No

TypeScript

Full TypeScript support with strict mode enabled:

import { slug } from "@lpm.dev/neo.slug";
import type { SlugOptions, UniqueSlugOptions } from "@lpm.dev/neo.slug";

const options: SlugOptions = {
  separator: "-",
  lowercase: true,
  strict: false,
  trim: true,
};

const result: string = slug("Hello World", options);

const uniqueOptions: UniqueSlugOptions = {
  maxAttempts: 25,
  signal: AbortSignal.timeout(2_000),
};

Browser Support

Works in all modern browsers and Node.js 18+:

  • Chrome, Firefox, Safari, Edge (latest 2 versions)
  • Node.js 18+
  • Deno, Bun

License

MIT

lpmslugslugifyurlurl-slugpermalinkseofriendly-urlclean-urltransliteratetransliterationunicodei18ndiacriticsunique-slugtypescriptzero-dependencytree-shakeableesmmodern