Explain Codes LogoExplain Codes Logo

How to convert a Title to a URL slug in jQuery?

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Feb 15, 2025
TLDR

Swiftly slugify a title using jQuery with .toLowerCase(), regex, and replace() magic:

var title = "Sample Title for Slug!"; var slug = title.toLowerCase() .replace(/\s+/g, '-') // Transforming spaces into running hyphens .replace(/[^\w-]+/g, ''); // Abandoning those non-alphanum characters

The outcome: sample-title-for-slug.

Code in detail: Unpacking the mystery

Let's understand the magic line-by-line:

  1. Trimming the fat: Remove extra whitespace at the beginning and end of your title.

    var title = " Sample #Title! For Slug? "; var slug = title.trim();
  2. Going incognito: Transform all uppercase letters to lowercase.

    slug = slug.toLowerCase();
  3. Joining the dash party: Replace any spaces with hyphens.

    slug = slug.replace(/\s+/g, '-'); // Who let the spaces out? Woo woo woo woo
  4. Cleaning up the mess: Remove all non-alphanumeric characters—We like our URLs neat and clean!

    slug = slug.replace(/[^\w-]+/g, ''); // Yeet everything that's non-alphanum
  5. The hyphen diet: Hyphens love to party. But sometimes, there are too many. Cut down on consecutive hyphens.

    slug = slug.replace(/-+/g, '-'); // Keeping those hyphens in check, nobody likes -'stutters'- in their slugs

Tackling peculiarities: Elevating the code

Wrestling with special characters

Multilingual and accented characters can be tricky. To include such characters in your slugs, replace these special characters with their alphanumeric equivalents. For instance, you might want to replace é with e.

function convertToSlug(text) { var charMap = { 'é': 'e', 'ö': 'o', 'ü': 'u' }; // Maximize this map as you need var slug = text.replace(/[^\w ]/g, function(char) { return charMap[char] || char; }) .toLowerCase() .replace(/\s+/g, '-') // Replace spaces with hyphens .replace(/[^\w-]+/g, '') // Remove residues that aren't alphanum .replace(/-+/g, '-'); // Keep those hyphens under control return slug; }

Real-time slug updates: Feeling responsive

Want to update your URLs in real-time? Here's your ticket: jQuery's keyup event.

$('#titleInput').on('keyup', function() { var title = $(this).val(); var slug = title.toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w-]+/g, '') .replace(/-+/g, '-'); $('#slugOutput').text(slug); });

T'S and C's

  • Always test your slug function with a variety of inputs to ensure it works well across all scenarios.
  • While jQuery simplifies the DOM manipulation, it might make your slug creation a tad slow. Remember, the hare only wins until the tortoise upgrades his server to SSD.
  • If your needs are complex—like managing special language characters or symbols, consider using a library such as "SpeakingURL"