Exercise 1: Slugify (URL-friendly)

Problem Statement

Create a function `slugify(text)`. Rules: lowercase, trim, spaces → dash, remove non-alphanumeric, collapse multiple dashes.

Sample Output:

slugify("Hello World!") => "hello-world"
slugify("  My First Post  ") => "my-first-post"

Solution

const slugify = (text) =>
  String(text ?? '')
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9\\s-]/g, '')
    .replace(/\\s+/g, '-')
    .replace(/-+/g, '-');

Explanation

Overall Goal:

  • Text ko URL-friendly slug me convert karna.
  • Rules: lowercase, spaces → dashes, special chars remove, clean format.

Line 1-2: String conversion

  • const slugify = (text) => → function header.
  • String(text ?? '') → nullish coalescing: null/undefined ho to empty string.

Line 3: Trim

  • .trim() → start aur end se spaces remove.
  • Example: " Hello World ""Hello World".

Line 4: Lowercase

  • .toLowerCase() → sabhi characters ko lowercase me convert.
  • Example: "Hello World""hello world".

Line 5: Remove special characters

  • .replace(/[^a-z0-9\\s-]/g, '')
  • [^a-z0-9\\s-] → regex character class:
  • ^ → negation (NOT these characters).
  • a-z → lowercase letters.
  • 0-9 → digits.
  • \\s → whitespace (space, tab, newline).
  • - → dash (allowed character).
  • /g → global flag (sabhi matches replace).
  • '' → replacement (remove, empty string).
  • Example: "Hello@World#123""helloworld123".

Line 6: Spaces to dashes

  • .replace(/\\s+/g, '-')
  • \\s+ → one or more whitespace characters.
  • '-' → replace with single dash.
  • Example: "hello world""hello-world".

Line 7: Collapse multiple dashes

  • .replace(/-+/g, '-')
  • -+ → one or more dashes.
  • '-' → replace with single dash.
  • Example: "hello---world""hello-world".

Real world:

  • Blog post URLs: "My First Post" → "my-first-post".
  • Product URLs: "iPhone 15 Pro" → "iphone-15-pro".
  • SEO-friendly URLs banane ke liye.

Navigation

Previous

No previous exercise

Next

Exercise 2

View All Categories