JAVASCRIPT

Validate URL Slug or Permalink with Regex

Ensure clean and SEO-friendly URL slugs or permalinks using a regex pattern that permits lowercase letters, numbers, and hyphens.

function isValidSlug(slug) {
  // Allows lowercase letters, numbers, and hyphens, no leading/trailing hyphens.
  const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
  return slugRegex.test(slug);
}

// Examples:
// console.log(isValidSlug("my-awesome-post")); // true
// console.log(isValidSlug("product-id-123")); // true
// console.log(isValidSlug("category")); // true
// console.log(isValidSlug("bad_slug")); // false (contains underscore)
// console.log(isValidSlug("-leading-hyphen")); // false
// console.log(isValidSlug("trailing-hyphen-")); // false
// console.log(isValidSlug("double--hyphen")); // false (optional based on preference, current one makes this false)
How it works: This JavaScript function provides a regular expression to validate URL slugs or permalinks. The pattern ensures that a slug consists only of lowercase alphanumeric characters and single hyphens, preventing leading/trailing hyphens and multiple consecutive hyphens, which is crucial for clean and SEO-friendly URLs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs