Last Updated: February 25, 2016
·
735
· dhaya

Convert a String to a valid URL slug

To get an URL slug from a string (a title, a name, etc.) just add this method to the String Class prototype:

String.prototype.toSlug = function ( ) {
  var from = 'àáäâèéëêìíïîòóöôùúüûñç',
    to = 'aaaaeeeeiiiioooouuuunc',
    expression = new RegExp(from.split('').join('|'), 'g'),
    str = this.toString();
    return str.toLowerCase().replace(expression, function ( m ) {
        return to[from.indexOf(m)];
    }).replace(/[^a-z0-9\-]+/g, '-');
}