JAVASCRIPT

Validating URL-Friendly Slugs with Regex

Use a regular expression in JavaScript to validate if a string is a valid, URL-friendly slug, ensuring it contains only lowercase letters, numbers, and hyphens.

function isValidSlug(slug) {
  // A slug should only contain lowercase letters, numbers, and hyphens.
  // It should not start or end with a hyphen, nor have consecutive hyphens.
  const slugRegex = new RegExp(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
  return slugRegex.test(slug);
}

// Examples:
console.log(isValidSlug("my-awesome-post"));         // true
console.log(isValidSlug("another-post-123"));       // true
console.log(isValidSlug("invalid Slug"));           // false (space)
console.log(isValidSlug("-start-with-hyphen"));    // false
console.log(isValidSlug("end-with-hyphen-"));      // false
console.log(isValidSlug("consecutive--hyphens")); // false
How it works: This `isValidSlug` function uses a regular expression to determine if a given string adheres to common URL slug conventions. The regex `/^[a-z0-9]+(?:-[a-z0-9]+)*$/` ensures that the slug starts and ends with an alphanumeric character (`[a-z0-9]+`) and allows hyphens only in between alphanumeric sequences (`(?:-[a-z0-9]+)*`). This prevents leading/trailing hyphens and consecutive hyphens, which are typically undesirable in clean URLs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs