Menu

A slug is nothing more than a sanitized version of a string where usually spaces and punctuation are replaced by separators. A typical example of a slug is the permanent link generated by WordPress. In this article we'll see how to create a slug from a string by using jQuery.

We need to sanitize our string by replacing all the occurrences of non-alphabetic characters with a separator (-). Since these special characters can occur at the beginning and at the end of our string, we also need to suppress them in such cases.

First, however, we have to trim our string by using the jQuery's $.trim() utility function. This will eliminate any unnecessary whitespace:

var slug = function(str) {
    var $slug = '';
    var trimmed = $.trim(str);
    $slug = trimmed.replace(/[^a-z0-9-]/gi, '-').
    replace(/-+/g, '-').
    replace(/^-|-$/g, '');
    return $slug.toLowerCase();
}

Here's an example:

$('#slug').text(slug($('#test').text()));

You can see the demo below.

Demo

Live demo

Share: