Skip to content

Instantly share code, notes, and snippets.

@kapkaev
Forked from sam/Slug.scala
Created August 4, 2017 17:17
Show Gist options
  • Save kapkaev/a1852f2a6244ecc6f73a7d1d7f3ba266 to your computer and use it in GitHub Desktop.
Save kapkaev/a1852f2a6244ecc6f73a7d1d7f3ba266 to your computer and use it in GitHub Desktop.
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