How to convert a Title to a URL slug in jQuery?

I have no idea where the 'slug' term came from, but here we go:

function convertToSlug(Text) {
  return Text.toLowerCase()
             .replace(/ /g, '-')
             .replace(/[^\w-]+/g, '');
}

The first replace method will change spaces to hyphens, second, replace removes anything not alphanumeric, underscore, or hyphen.

If you don't want things "like - this" turning into "like---this" then you can instead use this one:

function convertToSlug(Text) {
  return Text.toLowerCase()
             .replace(/[^\w ]+/g, '')
             .replace(/ +/g, '-');
}

That will remove hyphens (but no spaces) on the first replace, and in the second replace it will condense consecutive spaces into a single hyphen.

So "like - this" comes out as "like-this".


var slug = function(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();

  // remove accents, swap ñ for n, etc
  var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
  var to   = "aaaaaeeeeeiiiiooooouuuunc------";
  for (var i = 0, l = from.length; i < l; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
           .replace(/\s+/g, '-') // collapse whitespace and replace by -
           .replace(/-+/g, '-'); // collapse dashes

  return str;
};

and try

slug($('#field').val())

original by: http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/


EDIT: extended for more language specific chars:

var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆĞÍÌÎÏİŇÑÓÖÒÔÕØŘŔŠŞŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇğíìîïıňñóöòôõøðřŕšşťúůüùûýÿžþÞĐđßÆa·/_,:;";
var to   = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------";

First of all, regular expressions should not have surrounding quotes, so '/\s/g' should be /\s/g

In order to replace all non-alphanumerical characters with dashes, this should work (using your example code):

$("#Restaurant_Name").keyup(function() {
  var Text = $(this).val();
  Text = Text.toLowerCase();
  Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
  $("#Restaurant_Slug").val(Text);        
});

That should do the trick...