Last active
November 14, 2015 00:02
-
-
Save primaryobjects/b56189e52a3f0e3cfdbf to your computer and use it in GitHub Desktop.
R method to convert a sentence into a friendly url.
This file contains hidden or 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
# | |
# 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