Skip to content

Instantly share code, notes, and snippets.

Forked from sam/Slug.scala
Created August 4, 2017 17:17
What would you like to do?
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