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.


Comments

  1. [...] jQuery Slug Plugin Voilà un plugin qui permet de nettoyer une chaine de caractères pour pouvoir ensuite l’utiliser dans une URL (Slug) [...]

  2. Viddo says:

    Hey, neat idea! Found this because I was looking for this functionality. However it does not fit my case without modification why I would like to contribute with some extra options. Why not put it on Github or similar for everyone to improve it?

  3. Leo Caseiro says:

    Sorry, but this plugin have somes bugs:

    Bug 1:
    When your string to start on space
    Title: ” The test String”
    Slug: -the-test-string

    Bug 2:
    When your string to finish on space
    Title: “The test String ”
    Slug: the-test-string-

    -
    Solution1 [http://docs.jquery.com/Utilities/jQuery.trim]
    The $.trim() function on jQuery
    Ex: slugcontent = $.trim(slugcontent);

    ——
    Bug 3:
    When your string has 2 special caracters or more glued and without space:
    Title: “The test!!String”
    Slug: -the-teststring

    -
    Solution 2
    Replace this RegExp (/[^a-zA-Z0-9\-]/g,”) for (/[^a-zA-Z0-9\-]/g,’-')
    Ex: var finishedslug = slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,’-');

    ——
    Bug 4:
    When your string has 2 hifens or more:
    Title: “-The test String”
    Slug: -the-test–string

    -
    Solution 3
    Ex: finishedslug = finishedslug.replace(/[-]{2,}/g,’-');

    ——
    Bug 5:
    When your string to start on hyphen
    Title: “The test String-”
    Slug: the-test-string-

    Bug 6:
    When your string to finish on hyphen
    Title: The test String-
    Slug: the-test-string-

    -
    Solution 4
    RegExp: /(^[-])|([-]$)/
    finishedslug = finishedslug.replace(/(^[-])|([-]$)/g,”);

    ——

    All script with my solutions:
    makeSlug = function() {
    var slugcontent = jQuery.trim($this.val());
    var slugcontent_hyphens = slugcontent.replace(/\s/g,’-');
    var finishedslug = slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,’-');
    finishedslug = finishedslug.replace(/[-]{2,}/g,’-');
    finishedslug = finishedslug.replace(/(^[-])|([-]$)/g,”);
    jQuery(‘input.’ + settings.slug).val(finishedslug.toLowerCase());
    jQuery(‘span.’ + settings.slug).text(finishedslug.toLowerCase());

    }

    /* Im from Brazil and my English not is good! */

  4. Leo Caseiro says:

    Sorry, but this Plugin not work to my Language (PT-BR)

    So, I need to create a new plugin for Convert a string to slug.

  5. Perry says:

    Hi Leo,

    It’s true that the first version of this plugin had many bugs, I’ve actually fixed them along the way but haven’t bothered to upload the changes yet. The most recent version is now on Google Code.

    I’m sorry that I haven’t added any support yet for internationalization, but a commenter named Veena did borrow some code from Django to handle “special characters” – http://dvanula.cz/jquery.slug2.js .

  6. BandonRandon says:

    Hey Perry,

    Thanks for posting the link to the Google Code link. I was hoping there was an update. I also took some of the suggestions leo (above) made above and took the library to re-write the makeSlug(); function in a way that I believe incorporates most of his fixes.

    Here is the “new” function:

    makeSlug = function() {
    var slug = jQuery.trim($this.val()) // Trimming recommended by Brooke Dukes – http://www.thewebsitetailor.com/2008/04/jquery-slug-plugin/comment-page-1/#comment-23
    .replace(/\s+/g,’-').replace(/[^a-zA-Z0-9\-]/g,’-').toLowerCase() // See http://www.djangosnippets.org/snippets/1488/
    .replace(/\-{2,}/g,’-') // If we end up with any ‘multiple hyphens’, replace with just one. Temporary bugfix for input ‘this & that’=>’this–that’
    .replace(/(^[-])|([-]$)/g,”); //recommended by Leo Caseiro to fix starting and ending on a hyphen http://www.thewebsitetailor.com/jquery-slug-plugin/comment-page-1/#comment-31
    $(‘input.’ + settings.slug).val(slug);
    $(‘span.’ + settings.slug).text(slug);

    }

    Thanks,
    Brooke Dukes

  7. Leo Caseiro says:

    Hi Perry,

    Unfortunately did not see the plugin Veena.

    But Thanks for help me.

  8. Enrico says:

    what about accénts and umlauts (ü)?

  9. Julian says:

    Hi Perry,

    I think your plugin is nice and very useful. For your info, I wrote an article in my blog mentioning this plugin and a tweak I did to use special chars like accents in Spanish.

    Maybe you are interested, and maybe you’d like to support something like that in your future versions (as @Enrico requested):

    http://www.netvivs.com/build-permalinks-slug-with-javascript-jquery

    Thanks.

  10. Bermon says:

    Thanks for the great plugin. I’ve taken some of the bugs mentioned by Leo and incorporated them into the script. I also added a couple of features:

    • The slug can be set as ‘customizable’ in the settings to show the input. Defaults to true.
    • Preload the slug text if the input has a value.

    Enjoy!

    jQuery(function($) {
    jQuery.fn.slug = function(options) {
    var settings = {
    slug: ‘slug’,
    hide: true,
    customizable: true
    };

    if(options) {
    jQuery.extend(settings, options);
    }

    $this = jQuery(this);

    jQuery(document).ready( function() {
    if (settings.hide) {
    jQuery(‘input.’ + settings.slug).after(“\/ Customize“);
    jQuery(‘input.’ + settings.slug).hide();
    }
    });

    makeSlug = function() {
    var slugcontent = $this.val().trim();
    var slugcontent_hyphens = slugcontent.replace(/\s/g,’-');
    var finishedslug = slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,”).trim();
    finishedslug = finishedslug.replace(/[-]{2,}/g,’-');
    finishedslug = finishedslug.replace(/(^[-])|([-]$)/g,”);
    jQuery(‘input.’ + settings.slug).val(finishedslug.toLowerCase());
    jQuery(‘span.’ + settings.slug).text(finishedslug.toLowerCase());
    }

    jQuery(this).keyup(makeSlug);

    if(settings.customizable) {
    jQuery(‘#custom-slug’).click(function(){
    jQuery(this).hide();
    jQuery(‘input.’ + settings.slug).fadeIn(‘fast’);
    return false;
    });
    } else {
    jQuery(‘#edit-slug’).remove()
    }

    if(jQuery(‘input’ + settings.slug).val() != ”){
    var slugValue = jQuery(‘input.’ + settings.slug).val();
    jQuery(‘span.’ + settings.slug).text(slugValue);
    }

    return $this;
    };
    })

  11. Dwayne says:

    Awesome plugin dude. Just used this in a little custom Codeigniter driven CMS I built.

  12. Charlie says:

    quick and dirty jquery solution with international characters support:

    hardcode 2 inputs: #title and #slug

    include this js: (it collapses hyphens and whitespace and converts international characters.)
    http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/

    and then:
    $(‘#title’).keyup(function() { $(“#slug”).val(string_to_slug($(“#title”).val())); });

  13. Perry says:

    Thanks Charlie,

    That’s a great function… could really simplify my plugin!

  14. BandonRandon says:

    It seems like this plugin has involved and been improved any plans to update it either here or on Google Code?

    Brooke

  15. [...] Sto sviluppando un nuovo progetto e mi sono trovato nella necessità di creare qualcosa tipo il generatore di permalink di wordpress (altrimenti detto slug). Cercando qua e là un plugin jquery, ho trovato questo jquery slug plugin. [...]

  16. Hi Perry,
    I’m using your plugin: really a very good plugin.
    I’ve changed something and I would like you to take a look at my changes.
    I’ve tried to generalize its using.

    http://sipronunciaaigor.wordpress.com/2011/04/25/permalink-come-creare-uno-slug-stile-wordpress/

    Bye,
    Fabrizio

  17. [...] modifica che ho effettuato allo script originale (jQuery slug plugin di Perry) prevede l’utilizzo di <span class=”slug /> prima del campo di input per [...]

  18. Sebastian says:

    This plug in doesnt work whit 2 inputs …

  19. [...] a plugin for that! Tagged: javascript, jquery, questions, string /* * * CONFIGURATION [...]

  20. Ed says:

    How do I replace accents? My code:

    makeSlug = function() {
    var slug = jQuery.trim($this.val())
    .replace(/\s+/g,’-').replace(/[^a-zA-Z0-9\-]/g,’-').toLowerCase()
    .replace(/\-{2,}/g,’-')
    .replace(/(^[-])|([-]$)/g,”);
    $(‘input.’ + settings.slug).val(slug);
    $(‘span.’ + settings.slug).text(slug);

  21. mark says:

    unfortunately, the plugin has problems with common utf8 languages like german (äöüß umlauts)

    see https://github.com/cakephp/cakephp/blob/master/lib/Cake/Utility/Inflector.php#L167 for details on how to match those correctly

  22. tom estlack says:

    This is great – gives you the basics to modify as you need to. Thanks!!

  23. Bruno says:

    Take a look at: http://pastebin.com/gEc4ec3W

    Now it works with accents and ç!

Submit a Comment