Skip to content

Instantly share code, notes, and snippets.

@rufuspollock
Last active December 24, 2015 19:49
Show Gist options
  • Save rufuspollock/6853701 to your computer and use it in GitHub Desktop.
Save rufuspollock/6853701 to your computer and use it in GitHub Desktop.
Generate a slug (url-usable string) from a title or other string
// convert a title to a slug
//
// lowercase, replace ' ' by '-' and remove everything that is not alphanumeric, underscore or dash
var slug = title
.toLowerCase()
.replace(/ /g, '-')
.replace(/--+/g, '-')
.replace(/[^\w-]+/g, '')
;
def generate_slug(title):
slug = strip_accents(title)
slug = slug.lower()
slug = slug.strip().replace('.', '')
slug = slug.replace('/', ' ')
slug = slug.replace(' ', '-')
slug = slug.replace('- ', '-')
slug = slug.replace('--', '-')
import unicodedata
def strip_accents(s):
s = s.decode('utf8')
out = ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
return out.encode('utf8')
# usage
# generate_slug('My random title which can include accents and more ...')
@dsouzadyn
Copy link

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment