Skip to content

Instantly share code, notes, and snippets.

@sam
Created March 21, 2013 13:52
Show Gist options
  • Save sam/5213151 to your computer and use it in GitHub Desktop.
Save sam/5213151 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
@ferodss
Copy link

ferodss commented Nov 22, 2013

Very nice man!! tks

@raychenon
Copy link

raychenon commented May 30, 2017

4 years later and I use it for my project .
Thanks

@macalinao
Copy link

thanks!!!

@raychenon
Copy link

Still after 7 years, it rocks.
I re adapted into Kotlin
https://gist.github.com/raychenon/8fac7e5fb41364694f00e6ce8b8c32a8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment