Skip to content

Instantly share code, notes, and snippets.

@markembling
Last active December 6, 2016 18:17
Show Gist options
  • Save markembling/b2f57d72ce914a92e604f681f6831adc to your computer and use it in GitHub Desktop.
Save markembling/b2f57d72ce914a92e604f681f6831adc to your computer and use it in GitHub Desktop.
// 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