Slugify URLs using Javascript

To generate human-readable url slugs from any ordinary string, you can uyse the following code snippet in your javascript. You can use it as a function or as an angular factory method

Javascript Function:

var slugify = function(text){
        return text.toString().toLowerCase()
               .replace(/\s+/g, '-')           // Replace spaces with -
               .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
               .replace(/\-\-+/g, '-')         // Replace multiple - with single -
               .replace(/^-+/, '')             // Trim - from start of text
               .replace(/-+$/, '');            // Trim - from end of text
        }

Angular Method:

angularAppName.factory('AppUtil', function(){
     return {
         slugify: function(text){
              return text.toString().toLowerCase()
                  .replace(/\s+/g, '-')           // Replace spaces with -
                  .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
                  .replace(/\-\-+/g, '-')         // Replace multiple - with single -
                  .replace(/^-+/, '')             // Trim - from start of text
                  .replace(/-+$/, '');            // Trim - from end of text
              }
         }               
 });