Skip to content
Advertisement

Regex to match a slug?

I’m having trouble creating a Regex to match URL slugs (basically, alphanumeric “words” separated by single dashes)

JavaScript

I’ve come up with this Regex: /[a-z0-9-]+$/ and while it restricts the string to only alphanumerical characters and dashes, it still produces some false positives like these:

JavaScript

I’m quite bad with regular expressions, so any help would be appreciated.

Advertisement

Answer

You can use this:

JavaScript

This will match:

  1. A sequence of alphanumeric characters at the beginning.
  2. Then it will match a hyphen, then a sequence of alphanumeric characters, 0 or more times.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement