WordPress-like slug generator

I’m building a site for a client at the moment that needs to be able to control the URLs for each of their pages (including sub pages etc), we need a WordPress-like slug generator!

So, I came up with this, which i imagine is very similar to WordPress achieve the same thing (essentially stripping out unwanted characters and spaces, replacing them with hyphens)

the html form (stripped bare)…

[code language=”html”]

<label for="link_title">Navigation Name</label>
<input id="link_title" type="text" name="link_title" value="<?php echo $this->link_title; ?>" />

<label for="link_slug">URL Slug</label>
<input id="link_slug" type="text" name="link_slug" readonly="readonly" value="<?php echo $this->link_slug; ?>" />

…and some javascript (well, jQuery)

[code lang=”js”]
$(‘#link_title’).on(‘keyup’, function()
var slug = $(this).val().replace(/[^a-zA-Z0-9-]/g, ‘-‘).toLowerCase().replace(/–+/g, ‘-‘);

an example

Enter some text into the Navigation Name input:


Neat script! I’m using it with a toggle checkbox to specify whether you can manually edit the slug field or not.

Do you know how closely it matches the WP title sanitizer output?


Really like this, nice and easy to use. I amended mine for pure javascript, and also modified it a little to remove the first “-” if a space was put at the first character in the sluggable field, and code to remove the trailing “-” until it was required…

this is what I got:

document.getElementById('link_title').onkeyup = function() {
var v = this.value.replace(/[^a-zA-Z0-9-]/g, '-').toLowerCase().replace(/--+/g, '-');
//remove the end slash until needed
if (v.substr(v.length-1) == '-') {
v = v.substr(0, v.length-1);

//remove first slash if it exists
if (v.substr(0, 1) == '-') {
v = v.substr(1);

document.getElementById('link_slug').value = v;

Leave a Reply

Your email address will not be published. Required fields are marked *