Javascript – Slug

A slug is a way to represent a title with a limited charset (only lowercase letter and dash) to be inserted in the url. Even if it is a common function there is no good enough implentation when you Google for it.

Here are the features I needed:

  • No multiple dashes. ---- is converted to -
  • No wrapping dashes. -title- is converted to title
  • Basic support for internationalization. Coût d'éclat is converted to cout-d-eclat Don't look at the spelling mistake!
  • Basic support for common signs. 13$ & 12€ is converted to 13-dollar-and-12-euro

Demo

You can try the demo and see if it fits your needs.

Code

var keys = keys || function (o) { var a = []; for (var k in o) a.push(k); return a; };
 
var slug = function (string) {
//  var accents = "àáäâèéëêìíïîòóöôùúüûñç";
  var accents = "\u00e0\u00e1\u00e4\u00e2\u00e8"
    + "\u00e9\u00eb\u00ea\u00ec\u00ed\u00ef"
    + "\u00ee\u00f2\u00f3\u00f6\u00f4\u00f9"
    + "\u00fa\u00fc\u00fb\u00f1\u00e7";
 
  var without = "aaaaeeeeiiiioooouuuunc";
 
  var map = {'@': ' at ', '\u20ac': ' euro ', 
    '$': ' dollar ', '\u00a5': ' yen ',
    '\u0026': ' and ', '\u00e6': 'ae', '\u0153': 'oe'};
 
  return string
    // Handle uppercase characters
    .toLowerCase()
 
    // Handle accentuated characters
    .replace(
      new RegExp('[' + accents + ']', 'g'),
      function (c) { return without.charAt(accents.indexOf(c)); })
 
    // Handle special characters
    .replace(
      new RegExp('[' + keys(map).join('') + ']', 'g'),
      function (c) { return map[c]; })
 
    // Dash special characters
    .replace(/[^a-z0-9]/g, '-')
 
    // Compress multiple dash
    .replace(/-+/g, '-')
 
    // Trim dashes
    .replace(/^-|-$/g, '');
};

Bonus

If you are bored, here is a little exercise for you. Can you find a and b such as

a >= b && a < = b
// true
 
a == b
// false
If you liked this article, you might be interested in my Twitter feed as well.
 
  • BigAB

    Very interesting and seems useful. Thank you for it.

    (bonus question a=null b=0)

  • http://vjeux.com vjeux

    Nice answer for the bonus question.

    I got this one: a = [], b = [] :)

 

Random Posts

  • October 12, 2011 -- Hook document.CreateElement (3)
    For a project I will talk later on, I need to hook the function document.createElement. The code I wanted to write was: var original = document.createElement; document.createElement = function (tag) { // Do something return original(tag); }; Problem However, there's a silly Javasc...
  • October 11, 2009 -- EPITA – Project Recap (0)
    It has been one month that the third year (called Ing1) of EPITA started and this is a recap of the interesting projects that I developed. malloc (1 week) The goal of this mini-project is to improve our knowledge of memory management by implementing the C standard library memory allocator (mallo...
  • January 22, 2010 -- Project – WoW Genuine (0)
    [caption id="attachment_988" align="alignright" width="175" caption="WoW Genuine"][/caption] Working on the World of Raids Guild Recruitment I needed to make sure the user was really member of the guild he claimed to represent. Since there is no official API and we don't want to ask for the user ...
  • January 16, 2012 -- Tech Companies Recruitment (2)
    I am happy to tell you that I am now a Facebook employee! A bit of history Two years ago, like many of you, I applied to Google (thanks tsuna). Obviously I didn't get in. I did not even made it to the second interview! After analysis, I screwed up everything! Spoken English is hard without ...
  • January 26, 2011 -- Javascript – jQuery Binary Ajax (5)
    I made a DataView API Wrapper to read binary data from either a string or a binary buffer. You probably want to load it from a file, so you need to make a XHR request. Sadly no ajax wrapper implement it yet. XHR and Binary In order to get a binary string one must use the charset=x-user-defined M...