Last active
July 27, 2017 05:21
-
-
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.
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 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