Turn Sentences into Slugs with JavaScript
This simple script converts a text string into a valid URL slug. It mixes jQuery with standard JavaScript, and can be easily adapted to pure JS. <!-- Example input element --> <input id="controlId" type="text" /> // Handles typing $(document).ready(function () { // If the Title is specified, avoid overwrite if ($('#controlId').val().length === 0) { $('#controlId').on('keypress', function () { $('#controlId').val(slugify($('#controlId').val().toLowerCase())); }); } }); // Replacements function slugify(text) { text = text.replace(/[^-a-zA-Z0-9,&\s]+/g, ''); text = text.replace(/-/g, '_'); text = text.replace(/\s/g, '-'); return text; } Note (2025): For modern projects you may also want to normalize accents (é → e), trim repeated separators, and prefer input event instead of keypress. This post keeps the original 2010 logic. ...