Skip to content

Instantly share code, notes, and snippets.

@rdillmanCN
Last active July 27, 2017 05:21
Show Gist options
  • Save rdillmanCN/532da284016c46d353c40b95b30cec9f to your computer and use it in GitHub Desktop.
Save rdillmanCN/532da284016c46d353c40b95b30cec9f to your computer and use it in GitHub Desktop.
Convert a string into a standard page slug by removing non-alpha/numeric.
/**
* Convert a string into a standard slug by replacing all non alpha numeric characters
* with the passed separator or a hyphen. Also removing duplicate separators, and
* separators at the beginning or end of a slug.
*
* @param {String} tring The string slugify.
* @param {String} eparator The character or string to substitute.
* @returns {String|Undefined} The original, slugified, or undefined string.
*/
function slugify(string, separator) {
if (!string) {
return undefined;
}
if (typeof string !== 'string') {
return string;
}
var sep = typeof separator === 'string' ? separator : '-';
var regEx = new RegExp('[^a-z0-9]+', 'g');
var str = string.toLowerCase();
var slug = str.replace(regEx, sep);
return slug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment