Last Updated: February 25, 2016
·
981
· 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, '-');
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside