News and Insights

Create a slug with jQuery

January 19, 2011

These days’ web design URLs are not as meaningless as they used to be. Everyone always makes sure they use SEO-friendly URLs.

For this example let’s consider the title “Web design services London

Let’s say that FINN Partners have a website with a content management system and let’s consider the average CMS.

Most CMS will automatically generate an SEO friendly URL from the title of the page, as mentioned in this case, “Web design London”. This means that our SEO friendly URL will be Web-Design-London. But what if we don’t want that as the URL?

What we could do is have a field that allows us to enter the URL we want. Makes sense right? So we can add that, but isn’t it a bit of a bother remembering that you have to format it for a URL?

Well if you use our little function below it will sanitise your input string without it having to be done on the back-end.

$.fn.slug = function()
{

return this.val().replace(/[^a-zA-Z 0-9-]+/g,”).toLowerCase().replace(/s/g,’-‘)

};

This simple function will make sure that there are only alphanumeric characters and hyphens in your string so you can write your page URL without having to do it all in lower case and remembering to add a hyphen instead of a space.

You can use this function very easily; consider the example below:

$(‘#pageName’).val();

var pageSlug = $(‘#pageName’).val();

To use this function on the page slug variable you would simply append the jQuery function we have created.

var pageSlug = $(‘#pageName’).val().slug();

Easy, no?