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.
 
 

Related Posts

  • February 23, 2012 Dassault Systemes Javascript Evangelism Talk (0)
    I recently had the chance to do a 2-hour Javascript evangelism talk at Dassault Systèmes. Unfortunately the presentation has not been recorded. I reused my the presentation I did at EPITA at the beginning and added a second part with a lot of demos. I've written down notes about the […]
  • September 11, 2011 WebGL – Julia 3D Representation (0)
    At school we've been studying Lie Algebra and we were asked to make a 3D representation of a Lie Group. We chose to represent Julia Set in the Quaternion domain. We were really impressed to see that it was possible to generate many different forms given such a simple […]
  • December 7, 2011 C++: Fuzzy Search with Trie (0)
    For a school project, I had to make a part of a spell-check program. Given a dictionnary of words, you have to determine all the words that are within K mistakes of the original word. Trie As input, we've got a list of words along with their frequency. For example, with the following […]
  • August 20, 2011 Idea – mouseFreeze – A solution for Browser FPS Games (8)
    There is an open problem in porting real game into the web browser related to cursor handling. Problem Many games such as First-Person Shooters require the mouse to freely move, without the constraints of screen edges. However there is no such API in the browser to make this […]
  • August 29, 2011 Javascript: Improve Cache Performance: Reduce Lookups (2)
    In my Binary Decision Diagram Library, the performance bottleneck was the uniqueness cache. By reducing the number of cache lookup, it is possible to greatly improve the performances. Common pattern In order to test if the key is already in the cache, the usual pattern is to use key […]