JAVASCRIPT
Generating URL-Friendly Slugs
Create clean, SEO-friendly URL slugs from any string in JavaScript by normalizing characters and replacing spaces with hyphens.
function generateSlug(text) {
return text
.toString()
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, '') // Replace non-alphanumeric chars
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-'); // Replace multiple hyphens with single hyphen
}
// Examples:
console.log(generateSlug('My Awesome Blog Post Title!')); // my-awesome-blog-post-title
console.log(generateSlug('Another Title with Extra Spaces & Symbols @ 123')); // another-title-with-extra-spaces-symbols-123
console.log(generateSlug(' Slug with leading/trailing ')); // slug-with-leading-trailing
How it works: This JavaScript function `generateSlug` takes a string and converts it into a URL-friendly slug. It first converts the text to a string, makes it lowercase, and removes leading/trailing whitespace using `trim()`. Then, it applies three regex `replace()` operations: the first removes any character that is not a lowercase letter, number, space, or hyphen; the second replaces one or more spaces with a single hyphen; and the third replaces any sequence of multiple hyphens with a single hyphen. This results in a clean, consistent slug suitable for URLs.