Last active
December 6, 2016 18:17
-
-
Save markembling/b2f57d72ce914a92e604f681f6831adc to your computer and use it in GitHub Desktop.
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
// Mostly cribbed together from https://gist.github.com/mathewbyrne/1280286 | |
// Also: http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript | |
function _escapeRegex(str) { | |
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); | |
} | |
function slugify(str) { | |
str = str.trim(); | |
str = str.toLowerCase(); | |
// Remove accented characters and other specific swaps | |
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;=+"; | |
var to = "aaaaeeeeiiiioooouuuunc--------"; | |
for (var i = 0, l = from.length ; i < l ; i++) | |
str = str.replace(new RegExp(_escapeRegex(from.charAt(i)), 'g'), to.charAt(i)); | |
str = str.replace(/\s+/g, '-'); // Replace whitespace with dash | |
str = str.replace(/&/g, '-and-'); // Replace & with 'and' | |
str = str.replace(/\\/g, '-'); // Replace backslash with dash | |
str = str.replace(/[^\w\-]+/g, ''); // Remove all non-word chars | |
str = str.replace(/-+/g, '-'); // Replace multiple dashes with one | |
str = str.replace(/^-+|-+$/g, ''); // Remove leading and/or trailing dashes | |
return str; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment