Andrea Azzola

Tips and Techniques for Lifestyle Design

Turn Sentences into Slugs with JavaScript

Posted on [Permalink]

The 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;
}
Categories: