Created
December 14, 2012 06:38
-
-
Save jmillerdesign/4283199 to your computer and use it in GitHub Desktop.
Slugify a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert a human-readable string into a slug | |
* | |
* 'Sample input string!' gets converted to 'sample-input-string' | |
* | |
* @param {string} string Source string | |
* @param {integer} maxLength Maximum length of slug (defaults to 100) | |
* @return {string} Slug | |
*/ | |
var convertToSlug = function (string, maxLength) { | |
maxLength = maxLength || 100; | |
var rx = new RegExp('[^a-z0-9-]+', 'g'); | |
var slug = string.toLowerCase().replace(rx, '-').substr(0, maxLength); | |
if (slug.charAt(slug.length - 1) == '-') { | |
slug = slug.substr(0, slug.length - 1); | |
} | |
return slug; | |
} | |
// Usage: | |
$("#name").keyup(function () { | |
$("#slug").val(convertToSlug($(this).val())); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment