Generate URL Slugs in JavaScript: Step-by-Step Guide
Learn how to generate clean, SEO-friendly URL slugs in JavaScript with pure JS and the slugify library. Includes working code examples.
A URL slug is the human-readable portion of a web address that identifies a specific page. For example, in https://example.com/posts/my-first-post, the slug is my-first-post. Generating clean, SEO-friendly slugs in JavaScript is a common requirement for blogs, CMSs, and any application that builds dynamic URLs from user input.
How to Use the Slug Generator Tool
- Navigate to the Slug Generator on ToolSparkr.
- Paste or type any text — a post title, a product name, or a category label — into the input field.
- The tool instantly converts your text to a lowercase, hyphen-separated slug with all special characters removed.
- Click \"Copy\" to copy the result and paste it directly into your code or CMS.
Generating URL Slugs in JavaScript
You can create a lightweight slug function in pure JavaScript without any library. The approach is: convert to lowercase, replace accented characters, strip non-alphanumeric characters, and collapse multiple hyphens.
function generateSlug(text) {
return text
.toString()
.toLowerCase()
.normalize('NFD') // decompose accented chars
.replace(/[\\u0300-\\u036f]/g, '') // strip diacritics
.replace(/[^a-z0-9\\s-]/g, '') // remove non-alphanumeric
.trim()
.replace(/\\s+/g, '-') // spaces to hyphens
.replace(/-+/g, '-'); // collapse repeated hyphens
}
console.log(generateSlug('Hello, World! This is a Test'));
// Output: hello-world-this-is-a-test
console.log(generateSlug('Héllo Wörld'));
// Output: hello-world
If you are using Node.js and prefer a battle-tested library, slugify is the most popular choice:
// npm install slugify
const slugify = require('slugify');
const slug = slugify('My Blog Post Title!', {
lower: true,
strict: true, // strips special characters
trim: true
});
console.log(slug); // my-blog-post-title
Why Use a Slug Generator?
- SEO advantage — Clean slugs containing your target keyword improve search engine rankings.
- Readability — Short, descriptive URLs are more shareable and memorable for users.
- Consistency — Automating slug creation eliminates manual formatting errors across large datasets.
- Internationalisation — Proper normalisation handles accented and non-ASCII characters gracefully.
Tips and Best Practices
- Always
toLowerCase()before stripping characters — some regex patterns are case-sensitive. - Use
normalize('NFD')before removing diacritics to correctly handle languages like French, Spanish, and German. - Limit slug length to 60–75 characters to keep URLs concise in search results.
- Avoid stop words (a, an, the, and) in slugs when they add no keyword value.
- Once a slug is published, avoid changing it — broken links hurt SEO and user trust.
For quick one-off conversions, use the free Slug Generator on ToolSparkr — no installation required.