On this page
A monitor and an elephant sticking its trunk out of the monitor and drinking coffee from a cup.

Creating a slug from a string in JavaScript

Learn how to create URL-friendly slugs from strings in JavaScript, simplifying web development and enhancing SEO.

Creating a slug from a string in JavaScript can be useful for generating URLs or identifiers that are easy to read and share. A slug typically consists of lowercase letters, numbers, hyphens, or underscores, and it does not contain spaces or special characters.

Creating a slug from a string in JavaScript

Here’s how you can create a simple slugifier function in JavaScript:

Creating a slug from a string in JavaScript
function slugify(str, separator) {
    let text = str.toLowerCase().trim();

    const sets = [
      {
        from: '[ÀÁÂÃÄÅÆĀĂĄẠẢẤẦẨẪẬẮẰẲẴẶ]',
        to: 'a'
      },
      {
        from: '[ÇĆĈČ]',
        to: 'c'
      },
      {
        from: '[ÐĎĐÞ]',
        to: 'd'
      },
      {
        from: '[ÈÉÊËĒĔĖĘĚẸẺẼẾỀỂỄỆ]',
        to: 'e'
      },
      {
        from: '[ĜĞĢǴ]',
        to: 'g'
      },
      {
        from: '[ĤḦ]',
        to: 'h'
      },
      {
        from: '[ÌÍÎÏĨĪĮİỈỊ]',
        to: 'i'
      },
      {
        from: '[Ĵ]',
        to: 'j'
      },
      {
        from: '[IJ]',
        to: 'ij'
      },
      {
        from: '[Ķ]',
        to: 'k'
      },
      {
        from: '[ĹĻĽŁ]',
        to: 'l'
      },
      {
        from: '[Ḿ]',
        to: 'm'
      },
      {
        from: '[ÑŃŅŇ]',
        to: 'n'
      },
      {
        from: '[ÒÓÔÕÖØŌŎŐỌỎỐỒỔỖỘỚỜỞỠỢǪǬƠ]',
        to: 'o'
      },
      {
        from: '[Œ]',
        to: 'oe'
      },
      {
        from: '[ṕ]',
        to: 'p'
      },
      {
        from: '[ŔŖŘ]',
        to: 'r'
      },
      {
        from: '[ߌŜŞŠ]',
        to: 's'
      },
      {
        from: '[ŢŤ]',
        to: 't'
      },
      {
        from: '[ÙÚÛÜŨŪŬŮŰŲỤỦỨỪỬỮỰƯ]',
        to: 'u'
      },
      {
        from: '[ẂŴẀẄ]',
        to: 'w'
      },
      {
        from: '[ẍ]',
        to: 'x'
      },
      {
        from: '[ÝŶŸỲỴỶỸ]',
        to: 'y'
      },
      {
        from: '[ŹŻŽ]',
        to: 'z'
      },
      {
        from: `[·/_,:;']`,
        to: '-'
      }
    ];

    const replaceChar = (set) => {
      text = text.replace(new RegExp(set.from, 'gi'), set.to);
    };

    sets.forEach(replaceChar);

    text = text
      .toLowerCase()
      .replace(/\s+/g, '-')
      .replace(/&/g, '-and-')
      .replace(/[^\w-]+/g, '')
      .replace(/--+/g, '-')
      .replace(/^-+/, '')
      .replace(/-+$/, '');

    if (typeof separator !== 'undefined' && separator !== '-') {
      text = text.replace(/-/g, separator);
    }

    return text;
  }

Code explanation

This JavaScript function, slugify, is designed to convert a given string (str) into a URL-friendly format known as a slug. It does this by replacing characters that aren’t typically allowed in URLs with a specified character or sequence of characters, which by default is a hyphen (-). The function also allows an optional parameter separator to specify a different character or sequence to be used instead of the hyphen.

Here’s a breakdown of how it works:

  1. Input Parameter: the function takes two parameters:
    • str: the input string to be converted into a slug.
    • separator (optional): a character or string to replace hyphens with in the final slug. Defaults to -.
  2. Lowercase conversion: the input string is immediately converted to lowercase using .toLowerCase() method and then trimmed of leading and trailing whitespace with .trim() method. This ensures consistency regardless of case or extra spaces.
  3. Character mapping: an array named sets contains objects that map specific sequences of characters (represented as regular expressions) to replacement strings. These mappings cover a wide range of accented letters and special characters, ensuring they are replaced with basic ASCII equivalents or simplified forms. For example, accented vowels like ÀÁÂÃÄÅ are mapped to the letter a, and the sequence ß is mapped to ss.
  4. Replacement process:
    • The replaceChar function iterates over each object in the sets array, applying the from to to mapping to the input string. This is done using the String.prototype.replace method with a global (g) and case-insensitive (i) flag to ensure all instances of the matched characters are replaced.
    • After processing the sets, the function performs several more replacements on the string:
      • Replaces spaces with hyphens.
      • Replaces ampersands (&) with -and-.
      • Removes all characters that are not alphanumeric or hyphens.
      • Ensures there are no double hyphens by replacing them with single hyphens.
      • Trims hyphens from both the beginning and end of the string.
  5. Optional separator replacement: if a separator was provided and it’s not a hyphen, the function replaces all remaining hyphens in the string with the specified separator.
  6. Return value: finally, the function returns the processed slug as a string.

Example usage

Example of creating a slug from a string in JavaScript
const originalStr = "Hello, World! ñáéíóú";
const slug = CommonUtility.slugify(originalStr); // Assuming the function is part of a class named CommonUtility
console.log(slug); // Output might be something like "hello-world-n-a-e-i-o-u"

In this example, the original string includes accented characters and punctuation, which are transformed into a URL-friendly slug.

Related posts

Comments

Leave a Reply

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)