Last active
January 11, 2022 06:26
-
-
Save raychenon/8fac7e5fb41364694f00e6ce8b8c32a8 to your computer and use it in GitHub Desktop.
Slug transforms a raw text (ex: title) into a pretty URL
This file contains hidden or 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
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