Create SEO-Friendly URLs with JavaScript

Master string manipulation in JavaScript. Learn how to convert any page title into an SEO-friendly URL slug, handle duplicate slugs, and more.

A clean URL tells you what a page contains before you open it. Compare these examples:

example.com/post?id=48291

example.com/blog/how-to-slugify-a-string-in-javascript

The second URL is easier to read and understand. The final part of the URL is called a URL slug.

If you build a blog, content management system, product catalog, or JavaScript application, you may need to slugify page titles before using them in URLs.

In this guide, you will learn how to slugify a string in JavaScript. You will create a basic JavaScript slugify function, improve it for common input problems, handle accented characters, and learn how to manage duplicate URL slugs.

What Does Slugify Mean?

To slugify a string means converting normal text into a clean format that can be used as part of a URL.

For example, take this title:

How to Slugify a String in JavaScript

After conversion, the URL slug becomes:

how-to-slugify-a-string-in-javascript

A typical slugify process performs several operations:

  1. Convert uppercase letters to lowercase.
  2. Remove spaces from the beginning and end.
  3. Replace spaces with hyphens.
  4. Remove unwanted punctuation.
  5. Remove repeated separators.
  6. Return a clean URL slug.

The exact rules depend on your application. A simple English-language blog may need basic character handling. A multilingual publishing system needs a more carefully defined character policy.

What Is a URL Slug?

A URL slug is the readable section of a URL that identifies a specific page.

Consider this URL:

example.com/blog/javascript-slug-generator

The URL slug is:

javascript-slug-generator

A clean slug usually contains lowercase letters, numbers, and hyphens. Developers commonly use hyphens to separate words.

For example:

Original title:

Build a URL Slug Generator with JavaScript

Generated slug:

build-a-url-slug-generator-with-javascript

You can also use the Slugify tool at the provided website to convert text into a URL slug before adding similar logic to your application.

Why Should You Create Clean URL Slugs?

A descriptive URL slug gives the reader useful information about a page.

Compare these examples:

example.com/blog/javascript-string-methods

example.com/page.php?id=7392

The first URL gives you context about the page topic. The second URL does not explain what the page contains.

Clean URL slugs also make content management easier. When you work with analytics reports, content lists, redirects, or application routes, descriptive paths are easier to identify.

A useful URL slug should be:

  1. Relevant to the page topic.
  2. Easy to read.
  3. Consistent with your URL rules.
  4. Free from unnecessary punctuation.
  5. Stable after publication.

Avoid changing published slugs without a redirect plan. If an existing URL changes, old links may stop reaching the intended page.

How to Slugify a String in JavaScript

You can create a simple JavaScript slugify function with standard string methods and a regular expression.

Here is a basic example:

function slugify(text) {

  return text

    .toLowerCase()

    .trim()

    .replace(/\s+/g, “-“);

}

Now test the function:

slugify(“How to Slugify a String in JavaScript”);

Output:

how-to-slugify-a-string-in-javascript

This function performs three basic operations.

Convert the String to Lowercase

The first method is:

.toLowerCase()

Input:

JavaScript URL Generator

Output:

javascript url generator

Using lowercase output gives your generated slugs a consistent format.

Remove Extra Outer Whitespace

The next method is:

.trim()

Suppose the input contains spaces before and after the title:

   JavaScript Slug Generator

After trim(), the value becomes:

JavaScript Slug Generator

This step prevents unwanted separators from appearing at the beginning or end of the result.

Replace Spaces With Hyphens

The final operation in the basic function is:

.replace(/\s+/g, “-“)

Input:

javascript slug generator

Output:

javascript-slug-generator

The \s+ pattern matches one or more whitespace characters. The g flag applies the replacement across the entire string.

This basic slugify function works for simple input. Real titles often contain punctuation, symbols, repeated spaces, underscores, or accented characters. You need more processing for those cases.

Build a More Complete JavaScript Slugify Function

Consider this title:

JavaScript Tips & Tricks: Strings, Arrays, and More!

A basic space replacement would produce an unsuitable result because punctuation remains in the string.

You can create a more complete function:

function slugify(text) {

  return text

    .toLowerCase()

    .trim()

    .replace(/[^\w\s-]/g, “”)

    .replace(/[\s_]+/g, “-“)

    .replace(/-+/g, “-“)

    .replace(/^-+|-+$/g, “”);

}

Test it with this input:

slugify(“JavaScript Tips & Tricks: Strings, Arrays, and More!”);

Output:

javascript-tips-tricks-strings-arrays-and-more

This version handles several common slug generation requirements.

It converts text to lowercase. It removes unwanted punctuation. It replaces whitespace and underscores with hyphens. It also removes repeated hyphens and cleans separators from the beginning and end.

JavaScript Slugify Function Explained Step by Step

A short slug generator can contain several regular expressions. Understanding each step makes the function easier to modify and test.

Step 1: Convert Text to Lowercase

Use:

.toLowerCase()

Input:

Build A JavaScript Slug Generator

Output:

build a javascript slug generator

This gives all generated slugs the same letter case.

Step 2: Trim the Input String

Use:

.trim()

Input:

   slugify javascript string

Output:

slugify javascript string

The trim() method removes whitespace from both ends of the string.

Step 3: Remove Unwanted Characters

Use:

.replace(/[^\w\s-]/g, “”)

Input:

JavaScript: Slugs & URLs!

Result after this step:

JavaScript Slugs  URLs

The expression keeps word characters, whitespace, and hyphens. It removes many punctuation marks and symbols.

You should understand one limitation. In JavaScript regular expressions, \w does not preserve every letter from every writing system. If your application supports multiple languages, define your character handling requirements before using an ASCII-focused regular expression.

Step 4: Replace Spaces and Underscores With Hyphens

Use:

.replace(/[\s_]+/g, “-“)

Input:

javascript_slug generator

Output:

javascript-slug-generator

The + quantifier matches one or more consecutive characters from the group. Several spaces become one hyphen.

Step 5: Remove Duplicate Hyphens

Input may already contain separators.

Example:

JavaScript — Slug Generator

Use:

.replace(/-+/g, “-“)

Output:

javascript-slug-generator

This keeps the URL slug clean when the source text contains repeated hyphens.

Step 6: Remove Hyphens From the Start and End

Use:

.replace(/^-+|-+$/g, “”)

Input:

-javascript-slug-generator-

Output:

javascript-slug-generator

This final cleanup removes unnecessary separators from both ends.

How to Handle Accented Characters When You Slugify Text

Titles may contain accented characters.

Consider this text:

Café Déjà Vu

An ASCII-focused cleanup expression may remove accented letters instead of converting them into their base forms.

JavaScript provides the normalize() method, which can help with many accented Latin characters.

Use this version:

function slugify(text) {

  return text

    .normalize(“NFD”)

    .replace(/[\u0300-\u036f]/g, “”)

    .toLowerCase()

    .trim()

    .replace(/[^\w\s-]/g, “”)

    .replace(/[\s_]+/g, “-“)

    .replace(/-+/g, “-“)

    .replace(/^-+|-+$/g, “”);

}

Input:

Café Déjà Vu

Output:

cafe-deja-vu

The normalize(“NFD”) method decomposes many accented characters into a base character and a combining mark. The following replacement removes combining marks in the specified range.

This method does not provide complete transliteration for every language. If your website supports multilingual content, test the slugify function with actual content from each supported language.

Your application may need to preserve Unicode characters, use a transliteration process, or follow another URL policy.

How to Handle Empty Strings

A slug generator should handle empty input.

For example:

slugify(”   “);

After processing, the result is an empty string.

A utility function may return an empty value. A publishing application may need stricter validation.

You can check the result before saving it:

const slug = slugify(title);

if (!slug) {

  throw new Error(“A valid title is required to create a slug.”);

}

This prevents your application from creating a route without a usable slug.

The correct fallback depends on your system. Some applications may use a stable content ID. Others may prevent publication until the editor enters a valid title or slug.

How to Handle Duplicate URL Slugs

Two pages can have the same title.

For example:

JavaScript String Methods

If two posts use that title, both generate:

javascript-string-methods

The slugify function cannot determine whether that slug already exists in your database.

Your application must perform a uniqueness check.

A common pattern is:

javascript-string-methods

javascript-string-methods-2

javascript-string-methods-3

The application should check existing records before assigning the final URL.

For systems that process several publishing requests at the same time, uniqueness should also be enforced at the storage level. A JavaScript check alone may not prevent two concurrent requests from attempting to save the same slug.

Common Mistakes When You Slugify a String

A slugify function can be short, but several implementation mistakes can create inconsistent URLs.

Replacing Only the First Space

This code replaces only the first matching space:

text.replace(” “, “-“);

Input:

learn javascript string methods

Output:

learn-javascript string methods

Use a global regular expression:

text.replace(/\s+/g, “-“);

Output:

learn-javascript-string-methods

Allowing Repeated Hyphens

Without cleanup, input with repeated spaces or separators may create:

learn—javascript—today

Use:

.replace(/-+/g, “-“)

The result becomes:

learn-javascript-today

Ignoring Multilingual Content

An ASCII-focused expression may remove characters from non-English text.

Test your JavaScript slugify function against the actual languages your application supports. Do not assume one regular expression will handle every language correctly.

Automatically Changing Published Slugs

A page title may change after publication.

Original title:

JavaScript Slug Generator

Updated title:

How to Build a JavaScript Slug Generator

If your application regenerates the slug every time the title changes, the URL may also change.

A better publishing process is to generate the initial slug when the page is created. After publication, treat title changes and slug changes as separate actions.

If you change an existing URL, manage the old path according to your site’s redirect policy.

How to Use a Slug Generator in a JavaScript Application

A slugify function becomes useful when you connect it to a content form, blog editor, product page creator, or publishing workflow.

Example:

const title = “How to Build a Slug Generator”;

const slug = slugify(title);

console.log(slug);

Output:

how-to-build-a-slug-generator

You can then create a route:

const path = `/blog/${slug}`;

Result:

/blog/how-to-build-a-slug-generator

In a content management system, you can generate the initial slug from the title and show it in an editable field.

For example, the original title may be:

How to Slugify a String in JavaScript and Handle Common URL Formatting Problems

The generated slug would be:

how-to-slugify-a-string-in-javascript-and-handle-common-url-formatting-problems

An editor may choose a shorter version:

slugify-string-javascript

The final choice should remain clear and accurately describe the page.

Should You Remove Stop Words From URL Slugs?

Some slug generators remove common words such as “a,” “the,” “to,” or “in.”

You do not need to remove these words automatically.

Consider this slug:

how-to-slugify-a-string-in-javascript

After removing several common words, it could become:

how-slugify-string-javascript

The shorter result still communicates the topic, but the original version reads more naturally.

Choose your URL format based on clarity and your site’s publishing rules. Avoid rigid removal rules that produce unclear slugs.

Complete Reusable JavaScript Slugify Function

For many English-language titles and similar Latin-script input, the following function is a useful starting point:

function slugify(text) {

  if (typeof text !== “string”) {

    return “”;

  }

  return text

    .normalize(“NFD”)

    .replace(/[\u0300-\u036f]/g, “”)

    .toLowerCase()

    .trim()

    .replace(/[^\w\s-]/g, “”)

    .replace(/[\s_]+/g, “-“)

    .replace(/-+/g, “-“)

    .replace(/^-+|-+$/g, “”);

}

Test the function with different input values.

Example 1:

slugify(“Hello World”);

Output:

hello-world

Example 2:

slugify(”  JavaScript Slug Generator  “);

Output:

javascript-slug-generator

Example 3:

slugify(“Tips & Tricks for URLs!”);

Output:

tips-tricks-for-urls

Example 4:

slugify(“Café Déjà Vu”);

Output:

cafe-deja-vu

Example 5:

slugify(“JavaScript — URL Slugs”);

Output:

javascript-url-slugs

Before using the function in a production application, test it with real input from your website. Include punctuation, duplicate titles, empty values, accented characters, repeated separators, and all supported languages.

Test Your JavaScript Slug Generator

A small test set helps you find formatting problems early.

You can start with:

const tests = [

  “Hello World”,

  “JavaScript Slug Generator”,

  “Tips & Tricks!”,

  “Multiple     Spaces”,

  “Repeated — Hyphens”,

  “Café Déjà Vu”,

  “”,

  ”   “

];

tests.forEach((value) => {

  console.log(value, “=>”, slugify(value));

});

Check each result against your URL rules.

For a simple English-language website, your tests should confirm that:

  1. Uppercase letters become lowercase.
  2. Spaces become single hyphens.
  3. Repeated hyphens are removed.
  4. Outer whitespace is removed.
  5. Unwanted punctuation is removed.
  6. Empty input is handled safely.
  7. Supported accented characters produce the expected result.

Testing matters because URL rules often become harder to change after pages are published.

Create Clean URL Slugs With JavaScript

To slugify a string in JavaScript, define your URL rules first. Then convert the text to lowercase, trim unnecessary whitespace, remove unwanted characters, replace spaces with hyphens, and clean repeated separators.

A complete URL system also needs rules for duplicate slugs, title changes, empty input, redirects, and multilingual content.

Use the Slugify tool to convert titles into clean URL slugs, or use the JavaScript slugify function in this guide as a starting point for your blog, CMS, product catalog, or web application.

Share on Facebook
Share on Pinterest
Share on WhatsApp
Related posts
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


Post comment