Feb
20
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 totitle
- Basic support for internationalization.
Coût d'éclat
is converted tocout-d-eclat
Don't look at the spelling mistake! - Basic support for common signs.
13$ & 12€
is converted to13-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.