-
-
Save kapkaev/a1852f2a6244ecc6f73a7d1d7f3ba266 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