Turn Sentences into Slugs with JavaScript

Posted by Andrea on 2010-10-20 15:56

The following script allows you to turn a text string into a proper URL slug.
It's a mix of both jQuery and standard JavaScript, thought it can be easily turned into pure JS.  

// Handles typing
$(document).ready(function () {
	// If the Title is specified, avoids overwrite
	if ($('controlId').val().length == 0) {
		$('controlId').keypress(function () {
			$('controlId').val(slugify($('controlId').val().toLowerCase()));
		});
	}
});

// Replacements
function slugify(text) {
	text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
	text = text.replace(/-/gi, "_");
	text = text.replace(/\s/gi, "-");
	return text;
}

I use it in the administration section of this website, and in a few other projects.

I didn't wrote the slugify function by myself, but I don't even remember the original author :(.