Created
March 21, 2013 13:52
-
-
Save sam/5213151 to your computer and use it in GitHub Desktop.
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
package util | |
object Slug { | |
def apply(input:String) = slugify(input) | |
def slugify(input: String): String = { | |
import java.text.Normalizer | |
Normalizer.normalize(input, Normalizer.Form.NFD) | |
.replaceAll("[^\\w\\s-]", "") // Remove all non-word, non-space or non-dash characters | |
.replace('-', ' ') // Replace dashes with spaces | |
.trim // Trim leading/trailing whitespace (including what used to be leading/trailing dashes) | |
.replaceAll("\\s+", "-") // Replace whitespace (including newlines and repetitions) with single dashes | |
.toLowerCase // Lowercase the final results | |
} | |
} | |
// Example Usage: | |
Slug("This is the Title of my Blog Post!") | |
// String = "this-is-the-title-of-my-blog-post | |
// More "Magic" (though in Scala, it's not really, and for *simple* wrappers, pretty easy to see through): | |
implicit class StringToSlug(s:String) { | |
def slug = Slug(s) | |
} | |
// Now you can: | |
"This is the Title of my Blog Post!".slug | |
// String = "this-is-the-title-of-my-blog-post |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Still after 7 years, it rocks.
I re adapted into Kotlin
https://gist.github.com/raychenon/8fac7e5fb41364694f00e6ce8b8c32a8