Easy string case conversion in Go
s := "MIXED-caseString.test"| Converter | Output |
|---|---|
ToSnake(s) |
mixed_case_string_test |
ToUpperSnake(s) |
MIXED_CASE_STRING_TEST |
ToCamel(s) |
mixedCaseStringTest |
ToUpperCamel(s) |
MixedCaseStringTest |
ToKebab(s) |
mixed-case-string-test |
ToUpperKebab(s) |
MIXED-CASE-STRING-TEST |
If you are curious about the rules for converting strings, take a look at the test file for examples.
This package uses go modules and you should be able to use the latest release tag.
go get -u github.com/mrosales/stringcaseAll converters will remove any non-alphanumeric characters. That means things like emojis, punctuation, whitespace and other unicode characters will all be removed.
Before transforming the string, it is first split into words. This implementation tries to do the right thing™, but it may very well break some part of your use case. If you encounter something that seems incorrect, don't hesitate to file an issue. That being said, it may not be possible to update the library to cover every edge case.
The following cases trigger a word break:
-
Any non alphanumeric character (
[^a-zA-Z0-9]) -
Any whitespace (
\s+) -
Transitioning from lowercase to uppercase This attempts to respect Go's preference to capitalize acronyms and abbreviations.
fooBar->foo BarfooBAR->foo BARuserID->user IDuserIDFOO->user IDFOO(nothing we can really do about a string like this)
-
Transitioning from uppercase to lowercase
userIDBar->user ID Bar
github.com/iancoleman/strcase- This is a great library that I used for some time before this, but I felt
like the camelcase implementation in particular seemed inconsistent.
For example, I would prefer
ToCamel("fooBAR")to return"fooBar"rather than"fooBar". This is not necessarily wrong, but it does not match howToSnake("fooBAR")for that library returnsfoo_bar. - The change that this
stringcaselibrary makes is to first split the string into words and then join them in canonical fashion for each type of casing. This is slightly less efficient, but I find it to produce more predictable results.
- This is a great library that I used for some time before this, but I felt
like the camelcase implementation in particular seemed inconsistent.
For example, I would prefer
Released under the MIT License.