← all snippets

slugify

Converts a string into a URL-safe kebab-case slug — lowercase, accents stripped, non-alphanumeric runs collapsed to a single hyphen. Use it for URL paths, filenames, or IDs derived from a title.

JavaScript (Node) #10

Source

slugify.js
#!/usr/bin/env node
// Convert an input string to a URL-safe kebab-case slug.
// Usage: node slugify.js "Some Title Here!"
'use strict';
const input = process.argv[2];
if (!input) {
  console.error('usage: slugify.js "<text>"');
  process.exit(1);
}

// Strip Unicode combining marks (0x0300-0x036f) left behind by NFKD
// normalization, e.g. turns an accented e into a plain e.
const stripped = Array.from(input.normalize('NFKD'))
  .filter((ch) => {
    const c = ch.codePointAt(0);
    return c < 0x300 || c > 0x36f;
  })
  .join('');

const slug = stripped
  .toLowerCase()
  .trim()
  .replace(/[^a-z0-9]+/g, '-')
  .replace(/^-+|-+$/g, '');

console.log(slug);

Input

textstring — positional argument, the text to slugify, e.g. "Café Déjà Vu!" (quote it if it has spaces)

Output

Prints the lowercase, hyphen-separated slug to stdout, exit 0. Exits 1 with a usage message on stderr if no text argument is given.

Usage

$ node slugify.js "Café Déjà Vu!"
cafe-deja-vu

Config

No configuration required.

Security notes

  • Pure string transformation only — no eval, no dynamic code, no filesystem or network access.
  • The output charset is restricted to [a-z0-9-] by construction, so it's always safe to drop straight into a URL path or filename.