jQuery Slug Plugin

The jQuery Slug Plugin is a simple plugin which can be used to generate post slugs based on the content of a text input field.

In a few steps, a regex and the replace() method are used to sanitize the val() of the field that slug() is initialized on, and the sanitized slug is inserted as the value of a hidden input field (you specify the class of the field to insert to), and also inserted into a span so the user can see the post slug. Optionally you can choose to show the input field and hide the span.

Download jquery.slug.jsBlog post about the plugin

Usage

Of course, you’ll need to link to jQuery and the plugin itself:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.slug.js"></script>

Initializing the plugin is done like this:

<script type="text/javascript">
$(document).ready(function(){
$("#title").slug();
});
</script>

With the default settings, your markup should look like this:

<label for="title">Title:</label>
<input name="title" id="title" value="" /><br />
<label for="slug">Slug:</label>
<input name="slug" id="slug" value="" class="slug" />

There are only two options. Here is an example of initializing the plugin using both:

$("#title").slug({
slug:'permalink', // class of input / span that contains the generated slug
hide: false        // hide the text input, true by default
});

Demo:

Known Issues:

  • The plugin assumes that it is being called on an input, no error-checking is done on this
  • Pressing the space bar repeatedly as input causes the hyphens to pile up
  • Can only call the plugin for one element on a page

To-do:

  • Allowed characters should be configurable as an option. Currently it removes everything except a-z A-Z 0-9 and -.
  • It would be nice to add an optional ajax callback to be used to check whether the slug is unique.
  • Add a method to switch between an editable slug (hide:false) and the default span.