Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active November 14, 2015 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/b56189e52a3f0e3cfdbf to your computer and use it in GitHub Desktop.
Save primaryobjects/b56189e52a3f0e3cfdbf to your computer and use it in GitHub Desktop.
R method to convert a sentence into a friendly url.
#
# Converts text into a friendly url.
# Examples:
# friendlyUrl('She sells seashells by the seashore.') -> "she-sells-seashells-by-the-seashore"
# friendlyUrl('Learn To Program: 1,000 "Languages" in 2015.') -> "learn-to-program-1-000-languages-in-2015"
#
friendlyUrl <- function(text, sep = '-', max = 80) {
# Replace non-alphanumeric characters.
url <- gsub('[^A-Za-z0-9]', sep, text)
# Remove double separators (do this twice, in case of 4 or 3 repeats).
doubleSep <- paste(sep, sep, sep = '')
url <- gsub(doubleSep, sep, url)
url <- gsub(doubleSep, sep, url)
# Convert to lowercase and trim to max length.
url <- substr(tolower(url), 1, max)
# Trim leading and trailing separators.
gsub('^-+|-$', '', url)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment