Making slugs with JavaScript and regular expressions

You will sometimes want to generate a suitable URL ‘slug’ based on something the user has entered, such as the name of a blog post, or perhaps the name of a file which is being uploaded.

In order to ensure that your URLs are consistent, valid, and unambiguous, it is common to place the following restrictions on your slugs: allow only lowercase letters, numbers, and dashes (-). For example, a blog post called “Hello World!” might have a resulting slug of “hello-world”. Additionally, it is common to remove leading and trailing dashes from the final slug.

In this post, I’ll introduce a way of doing this in JavaScript. Read more Making slugs with JavaScript and regular expressions