Skip to content

Instantly share code, notes, and snippets.

@neojp
Created February 19, 2012 21:06
Show Gist options
  • Save neojp/1865776 to your computer and use it in GitHub Desktop.
Save neojp/1865776 to your computer and use it in GitHub Desktop.
Slugify a string, remove whitespace, convert accented letters and some signs
slugify = (str) ->
str = str.replace /^\s+|\s+$/g, ''
str = str.toLowerCase()
# remove accents, swap ñ for n, etc
from = "àáäâèéëêìíïîòóöôùúüûñ箩·/_,:;"
to = "aaaaeeeeiiiioooouuuuncrc------"
for i, character of from.split ''
str = str.replace new RegExp(character, 'g'), to.charAt i
# trademark sign
str = str.replace new RegExp('™', 'g'), 'tm'
# remove invalid chars
str = str.replace /[^a-z0-9 -]/g, ''
# collapse whitespace and replace by -
str = str.replace /\s+/g, '-'
# collapse dashes
str = str.replace /-+/g, '-'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment