Skip to content

Instantly share code, notes, and snippets.

@raychenon
Last active January 11, 2022 06:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save raychenon/8fac7e5fb41364694f00e6ce8b8c32a8 to your computer and use it in GitHub Desktop.
Save raychenon/8fac7e5fb41364694f00e6ce8b8c32a8 to your computer and use it in GitHub Desktop.
Slug transforms a raw text (ex: title) into a pretty URL
import java.text.Normalizer
/**
* Extension function
*/
fun String.slugify(): String =
Normalizer
.normalize(this, Normalizer.Form.NFD)
.replace("[^\\w\\s-]".toRegex(), "") // 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)
.replace("\\s+".toRegex(), "-") // Replace whitespace (including newlines and repetitions) with single dashes
.toLowerCase() // Lowercase the final results
// example
"How the Chihuahua Crossed the Road".slugify()
// output: "how-the-chihuahua-crossed-the-road"
// encapsulated in an object
object StringUtils{
fun slugify(input: String): String =
Normalizer
.normalize(input, Normalizer.Form.NFD)
.replace("[^\\w\\s-]".toRegex(), "") // 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)
.replace("\\s+".toRegex(), "-") // Replace whitespace (including newlines and repetitions) with single dashes
.toLowerCase() // Lowercase the final results
}
StringUtils.slugify("The quick brown Fox jumps over the lazy Dog")
// output: the-quick-brown-fox-jumps-over-the-lazy-dog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment