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

javascript, jquery, regex, slug, slugify

Solution

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, "");
}

console.log(convertToSlug("hello world!"));
console.log(convertToSlug("hello - world!"));

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, "-");
}

console.log(convertToSlug("hello world!"));
console.log(convertToSlug("hello - world!"));

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".

Problem

I'm working on an app in CodeIgniter, and I'm trying to make a field on a form dynamically generate the URL slug. What I'd like to do is remove the punctuation, convert it to lowercase, and replace the spaces with hyphens. So for example, Shane's Rib Shack would become shanes-rib-shack. Here's what I have so far. The lowercase part was easy, but the replace doesn't seem to be working at all, and I have no idea to remove the punctuation: ``` $("#Restaurant_Name").keyup(function() { var Text = $(this).val(); Text = Text.toLowerCase(); Text = Text.replace('/\s/g','-'); $("#Restaurant_Slug").val(Text); }); ```

Original source

Related problems