Using JavaScripts RegExp object to match URL slugs

Regular expressions (RegEx) are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects.[1] The RegExp object is used for matching text with a pattern.[2]

Match all lowercase characters, hyphens and numbers

The following pattern matches all lowercase characters:

  
[a-z]+
  

This would match e.g. simplestring.

To match all lowercase characters and hyphens the above pattern can be extended:

  
[a-z\-]+
  

This would match e.g. simple-string and simple-string-.

To still match all lowercase characters and hyphens but without allowing the path name to end with a hyphen the pattern could be changed to:

  
^[a-z]+(-[a-z]+)*$
  

This would match e.g. simple-string but not simple-string-.

To extend the pattern to support numbers (URI paths often contain numbers) use:

  
^[a-z\0-9]+(-[a-z\0-9]+)*$
  

This would match e.g. simple-string-1.

RegExp Validation

You can always validate your pattern with validation and testing tools[3].

References

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
  3. https://www.regextester.com/