Last active
December 24, 2015 19:49
-
-
Save rufuspollock/6853701 to your computer and use it in GitHub Desktop.
Generate a slug (url-usable string) from a title or other string
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 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, '') | |
; |
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
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 ...') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice