Created
August 22, 2011 00:28
-
-
Save casualjim/1161393 to your computer and use it in GitHub Desktop.
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
| object BackchatString { | |
| /** | |
| * Remove non-latin signs from text regular expression | |
| */ | |
| val NON_LATIN = """[^A-Za-z0-9\-\.]""".r | |
| /** | |
| * Remove whitespace regular expression | |
| */ | |
| val WHITESPACE = """[\s]""".r | |
| /** | |
| * Remove apostrophe regular expression | |
| */ | |
| val APOSTROPHE = """['`]""".r | |
| /** | |
| * Remove double underscores regular epxression | |
| */ | |
| val DOUBLE_UNDERSCORES = """(_|-)+""".r | |
| /** | |
| * Match at-sign regular expression | |
| */ | |
| val AT_SIGN = """\s*@\s*""".r | |
| /** | |
| * Match Ampersand regular expression | |
| */ | |
| val AMPERSAND = """\s*&\s*""".r | |
| /** | |
| * Match leading and trailing underscore regular expression | |
| */ | |
| val LEAD_TRAIL_UNDERSCORE = """\A[_\.]+|[_\.]+\z""".r | |
| /** | |
| * Creates a slug from a given string. This can be used as a url | |
| * | |
| * @param nameValue the string to make a slug from | |
| */ | |
| private def slugify(nameValue: String): String = { | |
| if (nameValue != null || nameValue.trim.length > 0) { | |
| val normalized = Normalizer.normalize(nameValue, Normalizer.NFD) | |
| val noApos = APOSTROPHE.replaceAllIn(normalized, "") | |
| val noAtSign = AT_SIGN.replaceAllIn(noApos, "at") | |
| val noAmper = AMPERSAND.replaceAllIn(noAtSign, "and") | |
| val noWhite = WHITESPACE.replaceAllIn(noAmper, "-") | |
| val almostThere = NON_LATIN.replaceAllIn(noWhite, "-") | |
| val singleUnderscored = DOUBLE_UNDERSCORES.replaceAllIn(almostThere, "-") | |
| val slug = LEAD_TRAIL_UNDERSCORE.replaceAllIn(singleUnderscored, "") | |
| slug.toLowerCase(Locale.ENGLISH) | |
| } else nameValue | |
| } | |
| } | |
| class BackchatString(s: String) { | |
| import BackchatString._ | |
| def asSlug = slugify(s) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment