Creating slugs with JavaScript

October 30, 2016 JavaScript

Every time that I write JavaScript, I find myself using this handy little function. A lot of the times, I use it to save or cache objects.

 * This function is used to create a sluged version of a string.
 * This is very useful when you want to prepare a key for a JSON object, for
 * example.
function slug(string, delimiter) {
  // Check to see if we passed a delimiter or not. We default
  // to using the underscore when one is not present
  delimiter = delimiter || '_';

  return string
    // Adds a space between letters when the string is camelCased
    .replace(/([a-z])([A-Z])/g, '$1 $2')

    // Make the string lower case, removing camel case

    // Remove special characters (also only alows lowercase) 
    // and replace them with the delimiter. This forces it to only allow
    // letters and numbers
    .replace(/[^a-z0-9]+/g, delimiter)

    // removes the trailing delimiter, in case one gets added
    .replace(new RegExp('^' + delimiter + '|' + delimiter + '$', 'g'), '');

I created a CodePen to show how this works, what it outputs. Check it out:

See the Pen Creating Slugs with Javascript by Adrian Ortega (@adrian-ortega) on CodePen.