Documentation
¶
Overview ¶
Package str transforms strings.
It holds the string work a generator, a router and a validator all need and none of them owns: Slug, Snake, Studly, Camel, Kebab, Headline, Plural, Singular, Limit, Squish, Mask, Is, UUID, ULID and Random, among some eighty others.
Functions and the chain ¶
Every transformation is a package-level function:
str.Studly(str.Singular(name))
Of returns a Stringable, which is the same transformations read the other way round:
str.Of(name).Singular().Studly().ToString()
They are one implementation with two spellings of the call, not two implementations: every Stringable method forwards to the function of the same name.
Optional arguments ¶
Go has no default arguments. A trailing run of optional arguments of one type arrives as a variadic tail -- Substr(value, start), Substr(value, start, length) -- and where a boolean or a second type follows them, every argument is spelled out instead, as on Limit and Replace.
What it does not do ¶
Nothing here is locale-aware, because locale-aware text needs CLDR data and this package carries no dependency to hold it. ASCII folds a table of Latin-1 and Latin Extended-A runes and drops what it does not know, and Transliterate puts a stand-in in the place of what that table cannot spell; Plural and Singular are English, and every irregular they get right is a line in a table in inflect.go, not a rule. UseLanguage refuses any language but English rather than answer in English under another one's name. Locale-correct pluralization belongs to the translation package, not this one.
Markdown and InlineMarkdown are this package's own renderer, so that no third-party dependency is needed to render a document. They cover CommonMark and the GitHub flavour's strikethrough, task lists, tables and bare-URL autolinking, and they take no options.
Index ¶
- Constants
- Variables
- func ASCII(s string) string
- func After(subject, search string) string
- func AfterLast(subject, search string) string
- func Apa(value string) string
- func Before(subject, search string) string
- func BeforeLast(subject, search string) string
- func Between(subject, from, to string) string
- func BetweenFirst(subject, from, to string) string
- func Camel(value string) string
- func CharAt(subject string, index int) (string, bool)
- func ChopEnd(subject string, needle ...string) string
- func ChopStart(subject string, needle ...string) string
- func Contains(haystack string, needles []string, ignoreCase bool) bool
- func ContainsAll(haystack string, needles []string, ignoreCase bool) bool
- func ConvertCase(value string, mode int) string
- func Counted(value string, count int) string
- func CreateRandomStringsNormally()
- func CreateRandomStringsUsing(factory func(length int) string)
- func CreateRandomStringsUsingSequence(sequence []string, whenMissing func(length int) string)
- func CreateULIDsNormally()
- func CreateULIDsUsing(factory func() string)
- func CreateULIDsUsingSequence(sequence []string, whenMissing func() string)
- func CreateUUIDsNormally()
- func CreateUUIDsUsing(factory func() string)
- func CreateUUIDsUsingSequence(sequence []string, whenMissing func() string)
- func Deduplicate(value string, character ...string) string
- func DoesntContain(haystack string, needles []string, ignoreCase bool) bool
- func DoesntEndWith(haystack string, needles ...string) bool
- func DoesntStartWith(haystack string, needles ...string) bool
- func EndsWith(haystack string, needles ...string) bool
- func Excerpt(text, phrase string, radius int, omission string) (string, bool)
- func Finish(value, cap string) string
- func FlushCache()
- func FreezeULIDs(callback ...func(ulid string)) string
- func FreezeUUIDs(callback ...func(uuid string)) string
- func FromBase64(value string, strict bool) (string, bool)
- func Headline(value string) string
- func Initials(value string, capitalize bool) string
- func InlineMarkdown(s string) string
- func Is(patterns []string, value string, ignoreCase bool) bool
- func IsASCII(value string) bool
- func IsJSON(value string) bool
- func IsMatch(patterns []*regexp.Regexp, value string) bool
- func IsULID(s string) bool
- func IsURL(value string, protocols ...string) bool
- func IsUUID(s string) bool
- func Kebab(value string) string
- func Language() string
- func Lcfirst(value string) string
- func Length(value string) int
- func Limit(value string, limit int, end string, preserveWords bool) string
- func Ltrim(value string, charlist ...string) string
- func Markdown(s string) string
- func Mask(value, character string, index int, length ...int) string
- func Match(pattern *regexp.Regexp, subject string) string
- func MatchAll(pattern *regexp.Regexp, subject string) []string
- func Numbers(value string) string
- func OrderedUUID() string
- func PadBoth(value string, length int, pad ...string) string
- func PadLeft(value string, length int, pad ...string) string
- func PadRight(value string, length int, pad ...string) string
- func ParseCallback(callback, fallback string) (string, string)
- func Pascal(value string) string
- func Password(length int, letters, numbers, symbols, spaces bool) string
- func Plural(s string, count ...int) string
- func PluralN(n int, singular string) stringdeprecated
- func PluralPascal(value string, count ...int) string
- func PluralStudly(value string, count ...int) string
- func Position(haystack, needle string, offset int) int
- func Random(n int) string
- func Remove(search []string, subject string, caseSensitive bool) string
- func Repeat(value string, times int) string
- func Replace(search, replace []string, subject string, caseSensitive bool) string
- func ReplaceArray(search string, replace []string, subject string) string
- func ReplaceEnd(search, replace, subject string) string
- func ReplaceFirst(search, replace, subject string) string
- func ReplaceLast(search, replace, subject string) string
- func ReplaceMatches(pattern *regexp.Regexp, replace, subject string, limit int) string
- func ReplaceStart(search, replace, subject string) string
- func ResetFactoryState()
- func Reverse(value string) string
- func Rtrim(value string, charlist ...string) string
- func Singular(s string) string
- func Slug(s, separator string) string
- func Snake(value, delimiter string) string
- func Squish(value string) string
- func Start(value, prefix string) string
- func StartsWith(haystack string, needles ...string) bool
- func Studly(value string) string
- func Substr(value string, start int, length ...int) string
- func SubstrCount(haystack, needle string, offset int, length ...int) int
- func SubstrReplace(value, replace string, offset int, length ...int) string
- func Swap(swap map[string]string, subject string) string
- func Take(value string, limit int) string
- func Title(value string) string
- func ToBase64(value string) string
- func Transliterate(s, unknown string, strict bool) string
- func Trim(value string, charlist ...string) string
- func ULID() string
- func UUID() string
- func UUID7() string
- func Ucfirst(value string) string
- func Ucsplit(value string) []string
- func Ucwords(value string, separators ...string) string
- func Unwrap(value, before string, after ...string) string
- func UseLanguage(lang string) error
- func WordCount(value string, characters ...string) int
- func WordWrap(value string, characters int, brk string, cutLongWords bool) string
- func Words(value string, words int, end string) string
- func Wrap(value, before string, after ...string) string
- type Stringable
- func (s Stringable) ASCII() Stringable
- func (s Stringable) After(search string) Stringable
- func (s Stringable) AfterLast(search string) Stringable
- func (s Stringable) Apa() Stringable
- func (s Stringable) Append(values ...string) Stringable
- func (s Stringable) Basename(suffix ...string) Stringable
- func (s Stringable) Before(search string) Stringable
- func (s Stringable) BeforeLast(search string) Stringable
- func (s Stringable) Between(from, to string) Stringable
- func (s Stringable) BetweenFirst(from, to string) Stringable
- func (s Stringable) Camel() Stringable
- func (s Stringable) CharAt(index int) (string, bool)
- func (s Stringable) ChopEnd(needle ...string) Stringable
- func (s Stringable) ChopStart(needle ...string) Stringable
- func (s Stringable) ClassBasename() Stringable
- func (s Stringable) Contains(needles []string, ignoreCase bool) bool
- func (s Stringable) ContainsAll(needles []string, ignoreCase bool) bool
- func (s Stringable) ConvertCase(mode int) Stringable
- func (s Stringable) Counted(count int) Stringable
- func (s Stringable) Deduplicate(character ...string) Stringable
- func (s Stringable) Dirname(levels ...int) Stringable
- func (s Stringable) DoesntContain(needles []string, ignoreCase bool) bool
- func (s Stringable) DoesntEndWith(needles ...string) bool
- func (s Stringable) DoesntStartWith(needles ...string) bool
- func (s Stringable) Dump(args ...any) Stringable
- func (s Stringable) EndsWith(needles ...string) bool
- func (s Stringable) Exactly(value string) bool
- func (s Stringable) Excerpt(phrase string, radius int, omission string) (string, bool)
- func (s Stringable) Explode(delimiter string, limit ...int) []string
- func (s Stringable) Finish(cap string) Stringable
- func (s Stringable) FromBase64(strict bool) Stringable
- func (s Stringable) Headline() Stringable
- func (s Stringable) Initials(capitalize bool) Stringable
- func (s Stringable) InlineMarkdown() Stringable
- func (s Stringable) Is(pattern []string, ignoreCase bool) bool
- func (s Stringable) IsASCII() bool
- func (s Stringable) IsEmpty() bool
- func (s Stringable) IsJSON() bool
- func (s Stringable) IsMatch(patterns []*regexp.Regexp) bool
- func (s Stringable) IsNotEmpty() bool
- func (s Stringable) IsULID() bool
- func (s Stringable) IsURL(protocols ...string) bool
- func (s Stringable) IsUUID() bool
- func (s Stringable) Kebab() Stringable
- func (s Stringable) Lcfirst() Stringable
- func (s Stringable) Length() int
- func (s Stringable) Limit(limit int, end string, preserveWords bool) Stringable
- func (s Stringable) Lower() Stringable
- func (s Stringable) Ltrim(characters ...string) Stringable
- func (s Stringable) Markdown() Stringable
- func (s Stringable) Mask(character string, index int, length ...int) Stringable
- func (s Stringable) Match(pattern *regexp.Regexp) Stringable
- func (s Stringable) MatchAll(pattern *regexp.Regexp) []string
- func (s Stringable) NewLine(count ...int) Stringable
- func (s Stringable) Numbers() Stringable
- func (s Stringable) PadBoth(length int, pad ...string) Stringable
- func (s Stringable) PadLeft(length int, pad ...string) Stringable
- func (s Stringable) PadRight(length int, pad ...string) Stringable
- func (s Stringable) ParseCallback(fallback string) (string, string)
- func (s Stringable) Pascal() Stringable
- func (s Stringable) Pipe(callback func(Stringable) string) Stringable
- func (s Stringable) Plural(count ...int) Stringable
- func (s Stringable) PluralPascal(count ...int) Stringable
- func (s Stringable) PluralStudly(count ...int) Stringable
- func (s Stringable) Position(needle string, offset int) int
- func (s Stringable) Prepend(values ...string) Stringable
- func (s Stringable) Remove(search []string, caseSensitive bool) Stringable
- func (s Stringable) Repeat(times int) Stringable
- func (s Stringable) Replace(search, replace []string, caseSensitive bool) Stringable
- func (s Stringable) ReplaceArray(search string, replace []string) Stringable
- func (s Stringable) ReplaceEnd(search, replace string) Stringable
- func (s Stringable) ReplaceFirst(search, replace string) Stringable
- func (s Stringable) ReplaceLast(search, replace string) Stringable
- func (s Stringable) ReplaceMatches(pattern *regexp.Regexp, replace string, limit int) Stringable
- func (s Stringable) ReplaceStart(search, replace string) Stringable
- func (s Stringable) Reverse() Stringable
- func (s Stringable) Rtrim(characters ...string) Stringable
- func (s Stringable) Scan(format string) []string
- func (s Stringable) Singular() Stringable
- func (s Stringable) Slug(separator string) Stringable
- func (s Stringable) Snake(delimiter string) Stringable
- func (s Stringable) Split(pattern any, limit ...int) []string
- func (s Stringable) Squish() Stringable
- func (s Stringable) Start(prefix string) Stringable
- func (s Stringable) StartsWith(needles ...string) bool
- func (s Stringable) String() string
- func (s Stringable) StripTags() Stringable
- func (s Stringable) Studly() Stringable
- func (s Stringable) Substr(start int, length ...int) Stringable
- func (s Stringable) SubstrCount(needle string, offset int, length ...int) int
- func (s Stringable) SubstrReplace(replace string, offset int, length ...int) Stringable
- func (s Stringable) Swap(swap map[string]string) Stringable
- func (s Stringable) Take(limit int) Stringable
- func (s Stringable) Tap(callback func(Stringable)) Stringable
- func (s Stringable) Test(patterns []*regexp.Regexp) bool
- func (s Stringable) Title() Stringable
- func (s Stringable) ToBase64() Stringable
- func (s Stringable) ToBoolean() bool
- func (s Stringable) ToDate(format ...string) (time.Time, error)
- func (s Stringable) ToFloat() float64
- func (s Stringable) ToInteger(base ...int) int
- func (s Stringable) ToString() string
- func (s Stringable) Transliterate(unknown string, strict bool) Stringable
- func (s Stringable) Trim(characters ...string) Stringable
- func (s Stringable) Ucfirst() Stringable
- func (s Stringable) Ucsplit() []string
- func (s Stringable) Ucwords(separators ...string) Stringable
- func (s Stringable) Unless(condition bool, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) Unwrap(before string, after ...string) Stringable
- func (s Stringable) Upper() Stringable
- func (s Stringable) Value() string
- func (s Stringable) When(condition bool, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenContains(needles []string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenContainsAll(needles []string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenDoesntEndWith(needles []string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenDoesntStartWith(needles []string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenEmpty(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
- func (s Stringable) WhenEndsWith(needles []string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenExactly(value string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenIs(pattern []string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenIsASCII(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
- func (s Stringable) WhenIsULID(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
- func (s Stringable) WhenIsUUID(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
- func (s Stringable) WhenNotEmpty(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
- func (s Stringable) WhenNotExactly(value string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenStartsWith(needles []string, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WhenTest(patterns []*regexp.Regexp, callback func(Stringable) Stringable, ...) Stringable
- func (s Stringable) WordCount(characters ...string) int
- func (s Stringable) WordWrap(characters int, brk string, cutLongWords bool) Stringable
- func (s Stringable) Words(words int, end string) Stringable
- func (s Stringable) Wrap(before string, after ...string) Stringable
Constants ¶
const ( CaseUpper = 0 CaseLower = 1 CaseTitle = 2 CaseFold = 3 )
The case modes ConvertCase accepts.
Variables ¶
var ErrLanguageNotSupported = errors.New("str: unsupported inflector language")
ErrLanguageNotSupported is returned by UseLanguage for a language this package carries no inflection rules for.
Functions ¶
func ASCII ¶
ASCII folds a string to ASCII: "Ação" becomes "Acao", "Straße" becomes "Strasse".
It is a table, not a transliterator: what it covers is Latin-1 Supplement and Latin Extended-A -- every language written in a Latin alphabet -- and a rune outside it is dropped rather than guessed at. Greek, Cyrillic and CJK come out empty, and a caller that slugs a title in one of those has to carry its own key.
func After ¶
After is everything past the first occurrence of search, or the whole string when search is empty or absent.
func AfterLast ¶
AfterLast is everything past the last occurrence of search, or the whole string when search is empty or absent.
func Apa ¶
Apa converts a string to APA-style title case, which leaves minor words of three letters or fewer lowercase unless they open the title or follow end punctuation.
See https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case.
func Before ¶
Before is everything up to the first occurrence of search, or the whole string when search is empty or absent.
func BeforeLast ¶
BeforeLast is everything up to the last occurrence of search, or the whole string when search is empty or absent.
func Between ¶
Between is the largest portion sitting after the first from and before the last to. The whole string comes back when either delimiter is empty.
func BetweenFirst ¶
BetweenFirst is the smallest portion sitting after the first from and before the first to. The whole string comes back when either delimiter is empty.
func CharAt ¶
CharAt returns the character at the given index, counting back from the end when the index is negative.
The second result is false when the index is out of range, because the empty string is not distinguishable from a character on its own.
func ChopEnd ¶
ChopEnd removes the first of the given needles that the string ends with, and leaves the string alone when it ends with none of them.
func ChopStart ¶
ChopStart removes the first of the given needles that the string starts with, and leaves the string alone when it starts with none of them.
func Contains ¶
Contains reports whether the haystack holds any one of the needles, comparing without regard to case when ignoreCase is set.
An empty needle never matches: Contains("anything", []string{""}, false) is false, not true.
The needles are a slice rather than a variadic tail because the case flag follows them.
func ContainsAll ¶
ContainsAll reports whether the haystack holds every one of the needles.
An empty list of needles is true, because there is nothing that fails. A needle that is the empty string is false, because Contains refuses it.
func ConvertCase ¶
ConvertCase converts a string in the given mode, which is one of CaseUpper, CaseLower, CaseTitle or CaseFold. There is no default: name the one wanted.
CaseFold is Unicode simple case folding, which for every alphabet this package can reach is lowercasing.
func Counted ¶
Counted is the count and the noun agreeing with it: Counted("rule", 1) is "1 rule" and Counted("rule", 3) is "3 rules".
The count goes through number.Format, so Counted("row", 1000) is "1,000 rows".
func CreateRandomStringsNormally ¶
func CreateRandomStringsNormally()
CreateRandomStringsNormally drops the random string factory, so Random generates again.
func CreateRandomStringsUsing ¶
CreateRandomStringsUsing sets the factory Random answers from; passing nil puts it back to normal.
func CreateRandomStringsUsingSequence ¶
CreateRandomStringsUsingSequence hands out the sequence one value per call, in order, ignoring the length that was asked for.
Once the sequence runs out whenMissing is called with that length; passing nil for it falls back to generating a real random string.
func CreateULIDsNormally ¶
func CreateULIDsNormally()
CreateULIDsNormally drops the ULID factory, so ULID generates again.
func CreateULIDsUsing ¶
func CreateULIDsUsing(factory func() string)
CreateULIDsUsing sets the factory ULID answers from; passing nil puts it back to normal.
func CreateULIDsUsingSequence ¶
CreateULIDsUsingSequence hands out the sequence one value per call, in order, and falls to whenMissing after it -- or to a real ULID when whenMissing is nil.
func CreateUUIDsNormally ¶
func CreateUUIDsNormally()
CreateUUIDsNormally drops the UUID factory, so UUID, UUID7 and OrderedUUID generate again.
func CreateUUIDsUsing ¶
func CreateUUIDsUsing(factory func() string)
CreateUUIDsUsing sets the factory UUID, UUID7 and OrderedUUID answer from; passing nil puts them back to normal.
func CreateUUIDsUsingSequence ¶
CreateUUIDsUsingSequence hands out the sequence one value per call, in order.
Once the sequence runs out whenMissing is called for every further value; passing nil for it falls back to generating a real UUID.
func Deduplicate ¶
Deduplicate collapses a run of the given character to one occurrence of it; passing no character deduplicates spaces.
The pattern is the quoted character followed by a plus, so a multi-character argument repeats only its last character: Deduplicate("a---b", "--") is "a--b". A character that is the empty string returns the value untouched.
func DoesntContain ¶
DoesntContain is Contains negated.
func DoesntEndWith ¶
DoesntEndWith is EndsWith negated.
func DoesntStartWith ¶
DoesntStartWith is StartsWith negated.
func EndsWith ¶
EndsWith reports whether the haystack ends with any one of the needles. An empty needle never matches.
func Excerpt ¶
Excerpt cuts an excerpt out of the text around the first case-insensitive occurrence of phrase, keeping radius characters on each side and marking a cut end with omission.
The second result is false when the phrase is not in the text.
func Finish ¶
Finish caps the string with a single instance of cap, collapsing a cap that is already there more than once: Finish("path//", "/") is "path/".
func FreezeULIDs ¶
FreezeULIDs makes every ULID from here on the one it returns, and with a callback the freeze lasts only for that call.
func FreezeUUIDs ¶
FreezeUUIDs makes every UUID from here on the one it returns.
With a callback the freeze lasts only for the length of that call and is lifted in a defer afterwards, whatever the callback does.
func FromBase64 ¶
FromBase64 decodes standard base64.
The second result is false when the decoding fails. Strict decoding refuses any character outside the alphabet, and both modes skip whitespace and stop at the first padding character.
func Headline ¶
Headline converts a string to a title-cased sentence: Headline("EmailNotificationSent") and Headline("email_notification_sent") are both "Email Notification Sent".
func Initials ¶
Initials keeps the first character of every whitespace-separated part, and uppercases them when capitalize is set: Initials("Paulo Ricardo Lima", false) is "PRL".
func InlineMarkdown ¶
InlineMarkdown renders only the inline part of CommonMark -- emphasis, code spans, links, images -- with no block element around it.
InlineMarkdown("**Hello World**") // "<strong>Hello World</strong>\n"
A heading marker or a list marker is left standing as text, because there is no block parser to read it.
The note on raw HTML in the comment on Markdown holds here too.
func Is ¶
Is reports whether the value matches any one of the patterns, where * stands for any run of characters, including none. Every other rune is literal, so a pattern is safe to build from configuration without escaping anything.
Is([]string{"admin/*"}, "admin/users", false) is true, and so is Is([]string{"*"}, anything, false).
It is not path.Match: * crosses a slash, because what this matches is a route name, an ability or a host, not a file name.
func IsURL ¶
IsURL reports whether the string is an absolute URL whose scheme is one of the protocols given, or one of the three hundred registered ones when none are given.
The shape it accepts is a scheme, optional basic auth, a host that is a domain of at least two characters or an IPv4 address or a bracketed IPv6 address, an optional port, and then path, query and fragment.
func IsUUID ¶
IsUUID reports whether s has the shape of a hyphenated UUID. Shape only: it says nothing about the version or the variant, because a caller checking an identifier off a request wants to know whether it can be looked up, not who made it.
func Length ¶
Length is the number of characters in the string, not the number of bytes, so Length("café") is 4.
func Limit ¶
Limit cuts the string to at most limit display columns and appends end when it had to cut.
Columns, not bytes: a full-width character counts as two. When preserveWords is true the cut is moved back to the last whitespace, and HTML tags and line breaks are removed first.
func Markdown ¶
Markdown renders CommonMark, with the GitHub flavour's strikethrough, task lists, tables and bare-URL autolinking, as HTML.
Markdown("# Hello") // "<h1>Hello</h1>\n"
Markdown("*hello*") // "<p><em>hello</em></p>\n"
Raw HTML passes through untouched. Rendering untrusted Markdown therefore renders untrusted HTML: sanitize it after this, before it reaches a page.
There is nothing to configure and there will not be: the renderer is this file, and one way to spell a document is enough.
func Mask ¶
Mask replaces a run of the string, starting at index, with the first character of character repeated: Mask("paulo@example.com", "*", 3, 8) is "pau********le.com".
A negative index counts back from the end. Passing no length runs to the end of the string; a length of zero masks nothing and returns the string untouched.
It is not redaction. The length of the answer still tells the reader how long the secret was, which for a password is more than it should learn.
func Match ¶
Match returns the first capture group of the first match, or the whole match when the pattern captures nothing, or the empty string when the pattern does not match at all.
The pattern arrives compiled, so a case-insensitive one is written regexp.MustCompile(`(?i)name`).
func MatchAll ¶
MatchAll returns the first capture group of every match, or every whole match when the pattern captures nothing. The slice is empty rather than nil when nothing matched.
func Numbers ¶
Numbers keeps the digits and drops everything else: Numbers("(11) 98765-4321") is "11987654321".
Digits means the ten ASCII ones.
func OrderedUUID ¶
func OrderedUUID() string
OrderedUUID is a time-ordered UUID: 48 bits of Unix milliseconds in front, the rest random, and the version nibble still reading 4.
It exists for the same reason UUID7 does -- an index that is written in order -- for a schema whose column is documented as holding a version 4 UUID.
func PadBoth ¶
PadBoth splits the padding between the two ends, giving the odd character to the right side.
func PadLeft ¶
PadLeft grows the string to the given number of characters by putting pad in front of it, repeating and cutting pad as needed; passing no pad uses a space.
A length no greater than the string already has returns it untouched, so PadLeft("hello", 3) is "hello" and not "hel". An empty pad returns it untouched too.
func ParseCallback ¶
ParseCallback splits a "Class@method" string into its two halves, and answers the whole string with the fallback when there is no at sign in it.
There is no null here: pass the empty string for a second half that stands for nothing.
func Pascal ¶
Pascal converts a string to Pascal case: Pascal("invoice_line") and Pascal("invoice-line") are both "InvoiceLine". Only the first letter of each dash-, underscore- or space-separated part is touched, so Pascal("HTTPServer") is "HTTPServer" and not "HttpServer".
It is Studly under the other name for the same convention, and the two are interchangeable in every call.
func Password ¶
Password is a random password of the given length, drawn from the sets that are switched on.
Password(32, true, true, true, false)
All five arguments are required, because Go has no default arguments.
Every set that is on contributes one character up front, so a password that asks for symbols has a symbol in it. Those characters count against the length and the rest is drawn from the sets together, then the whole thing is shuffled -- which is why a length shorter than the number of sets still comes back with one character from each and is longer than asked for.
With every set switched off there is nothing to draw from and the answer is empty.
func Plural ¶
Plural is the plural of an English noun -- "purchase_order" becomes "purchase_orders", "person" becomes "people", "knife" becomes "knives".
The optional count defaults to two. A count of one in either sign returns the word untouched, so Plural("rule", 1) is "rule".
It pluralizes the last word and leaves the rest alone, so a compound name keeps its shape: "sales_person" is "sales_people", not "sales_persons". The case of that word is carried over -- "Invoice" is "Invoices" and "INVOICE" is "INVOICES" -- because this names a table in one call site and a heading in the next.
A value that does not end in a letter, a digit or a non-ASCII rune is not a word and is returned untouched: "rule!" and "rule " stay as they are.
English pluralization has hundreds of exceptions and this handles the ones a schema meets. Everything the tables in this file do not name takes -s or -es by rule. A word that comes out wrong is a line to add there, not a rule to change.
func PluralPascal ¶
PluralPascal pluralizes the last word of a Pascal case string and leaves everything in front of it alone: PluralPascal("VerifiedHuman") is "VerifiedHumans". That last word is found by splitting in front of every capital, so PluralPascal("HTTPServer") is "HTTPServers". The optional count behaves as in Plural: a count of one returns the value untouched.
It is PluralStudly under the other name for the same convention, and the two are interchangeable in every call.
func PluralStudly ¶
PluralStudly pluralizes the last word of a studly caps string and leaves everything in front of it alone: PluralStudly("VerifiedHuman") is "VerifiedHumans".
That last word is found by splitting in front of every capital, which is why PluralStudly("HTTPServer") is "HTTPServers" and not "HTTPServer" with the run of capitals pluralized.
func Position ¶
Position is the character index of the first occurrence of needle at or after offset.
It returns -1 when the needle is absent, the way strings.Index does, because a character index is never negative.
func Random ¶
Random is n random alphanumeric characters, from the system source.
Use it for anything that has to be unguessable -- a token, a nonce, a password a machine invented. It is not a hash and not an identifier; UUID7 or ULID is what names a row.
CreateRandomStringsUsing stands in front of it, so a test can pin what it returns.
func Remove ¶
Remove deletes every occurrence of each search from the subject, matching without regard to case when caseSensitive is false.
func Repeat ¶
Repeat is the string written times over.
A negative count returns the empty string, as a count of zero does, because there is no shorter answer to give.
func Replace ¶
Replace replaces every occurrence of each search with the replacement standing at the same index, running the searches in order over the whole subject, and matches without regard to case when caseSensitive is false.
A search with no replacement opposite it is replaced with the empty string, which is why Replace([]string{"a", "b"}, []string{"x"}, "ab", true) is "x" and not "xx". An empty search matches nothing and is skipped.
func ReplaceArray ¶
ReplaceArray walks the occurrences of search from left to right and spends one replacement on each: ReplaceArray("?", []string{"8:30", "9:00"}, "from ? to ?") is "from 8:30 to 9:00".
When the replacements run out the search is left where it stands. An empty search returns the subject untouched.
func ReplaceEnd ¶
ReplaceEnd replaces search only where it ends the subject.
func ReplaceFirst ¶
ReplaceFirst replaces the first occurrence of search, and returns the subject untouched when search is empty or absent.
func ReplaceLast ¶
ReplaceLast replaces the last occurrence of search, and returns the subject untouched when search is empty or absent.
func ReplaceMatches ¶
ReplaceMatches replaces at most limit matches of the pattern, and every one of them when limit is negative.
The replacement expands a capture group as $1 or ${name}. A limit of zero replaces nothing.
func ReplaceStart ¶
ReplaceStart replaces search only where it begins the subject.
func ResetFactoryState ¶
func ResetFactoryState()
ResetFactoryState drops all three factories at once, which is what a test tears down with.
func Reverse ¶
Reverse reverses the string character by character, so a multi-byte rune survives the trip.
func Singular ¶
Singular is the singular of an English noun: "purchase_orders" becomes "purchase_order", "people" becomes "person", "knives" becomes "knife".
It is Plural read backwards, with the same tables and the same treatment of compounds and case. English does not invert cleanly -- "axes" is the plural of both "axe" and "axis", and "-ses" is "-se" in "houses" and "-s" in "buses" -- so where the ending is ambiguous this answers with the commoner word and the table in this file holds the corrections.
func Slug ¶
Slug is the text as an address: Slug("Josefin Sans Café", "-") is "josefin-sans-cafe".
The separator is required, as it is on Snake, because Go has no default arguments. Pass "" to run the words together.
It folds to ASCII first, so an accented rune becomes the letter it is built on instead of disappearing: two names differing only in their accents would otherwise slug to one and the same address.
An at sign becomes the word "at" before anything else happens, which is what keeps two addresses at different hosts from slugging to the same thing.
func Snake ¶
Snake converts a string to snake case with the given delimiter: Snake("PurchaseOrder", "_") is "purchase_order".
A delimiter goes in before every capital, one per capital, so Snake("HTTPServer", "_") is "h_t_t_p_server". A string that is already all lowercase letters is returned untouched, so Snake("foo-bar", "_") is "foo-bar" and not "foo_bar".
func Squish ¶
Squish trims both ends and collapses every run of whitespace inside the string to a single space.
The two Hangul filler characters count as whitespace here, because they are invisible and a person pasting text carries them in without knowing.
func Start ¶
Start begins the string with a single instance of prefix, collapsing a prefix that is already there more than once: Start("//api", "/") is "/api".
func StartsWith ¶
StartsWith reports whether the haystack begins with any one of the needles. An empty needle never matches.
func Studly ¶
Studly converts a string to studly caps: Studly("invoice_line") and Studly("invoice-line") are both "InvoiceLine".
Only the first letter of each dash-, underscore- or space-separated part is touched, so Studly("HTTPServer") is "HTTPServer" and not "HttpServer".
func Substr ¶
Substr returns the portion of the string given by start and length, counted in characters.
A negative start counts back from the end. A negative length stops that many characters short of the end. Passing no length runs to the end of the string.
func SubstrCount ¶
SubstrCount counts the non-overlapping occurrences of needle from offset onwards, in bytes.
An empty needle returns zero, because there is no count that answers the question.
func SubstrReplace ¶
SubstrReplace replaces the portion of the string given by offset and length, in bytes.
A negative offset counts back from the end, a negative length stops that many bytes short of the end, and passing no length replaces everything from offset onwards.
func Swap ¶
Swap applies a whole map of replacements in one left-to-right pass, so nothing a replacement produces is replaced again: Swap(map[string]string{"a": "b", "b": "a"}, "ab") is "ba".
The longest key that fits at a position wins, and an empty key is ignored.
func Take ¶
Take returns the first limit characters of the string, or the last limit characters when limit is negative.
func Title ¶
Title uppercases the first letter of every word and lowercases the rest of each one: Title("welcome EMAIL") is "Welcome Email".
A word starts after any character that is not a letter, which is what makes Title("hello-world") "Hello-World" and Title("o'neil") "O'Neil".
func Transliterate ¶
Transliterate writes the string in ASCII, putting unknown in the place of every rune it has no ASCII spelling for.
Transliterate("Ação", "?", false) // "Acao"
Transliterate("ⓐⓑⓒ", "?", false) // "abc"
Transliterate("🎂", "H", false) // "H"
The unknown spelling is required, because Go has no default arguments. Pass the empty string to drop what cannot be spelled, which is what ASCII does.
strict changes nothing: both modes answer from the tables in this package, and a script outside them -- Greek, Cyrillic, the CJK readings -- comes back as unknown either way.
func Trim ¶
Trim removes characters from both ends of the string. With no charlist it removes whitespace, the byte order mark, the zero width space and the left-to-right mark; with one it removes exactly the characters given.
func ULID ¶
func ULID() string
ULID is a 26-character Crockford base32 identifier: 48 bits of Unix milliseconds followed by 80 bits of randomness.
Sortable like UUID7 and shorter, with an alphabet that has no I, L, O or U in it, so it survives being read aloud and cannot spell a word. It is what to use where the value shows up in a URL.
CreateULIDsUsing and FreezeULIDs stand in front of it. It reads the clock, and a caller that has to pin the value uses those.
func UUID ¶
func UUID() string
UUID is a random version 4 UUID in the canonical 8-4-4-4-12 hyphenated form.
Random, which means unordered: a table with one of these as its primary key writes to a random leaf of the index on every insert. UUID7 is the one to reach for when the value is a key. This one is for a correlation id, a one-time token or anything a person may paste.
CreateUUIDsUsing and FreezeUUIDs stand in front of it, so a test can pin what it returns.
There is no error to return. Since Go 1.24 crypto/rand.Read cannot fail; when the system source is unavailable the program crashes rather than handing back a value that is not random.
func UUID7 ¶
func UUID7() string
UUID7 is a version 7 UUID: 48 bits of Unix milliseconds followed by 74 bits of randomness, in the same hyphenated form.
Sortable by generation time, which is what makes it usable as a primary key and as a cursor. It also tells anyone holding it when the row was created, so it is not the identifier for something whose age is private.
It reads the clock, and a caller that has to pin the value uses CreateUUIDsUsing, which stands in front of this the same way.
func Ucsplit ¶
Ucsplit splits a string into pieces in front of every uppercase letter, dropping the empty pieces: Ucsplit("EmailNotificationSent") is ["Email", "Notification", "Sent"].
func Ucwords ¶
Ucwords uppercases the first letter of the string and every lowercase letter that follows one of the separators; passing no separators uses space, tab and the line breaks.
Only a lowercase letter is touched: a part that already begins with a capital or a digit is left as it stands.
func Unwrap ¶
Unwrap removes before from the front of the value and after from the back, each only if it is there; passing no after repeats before.
func UseLanguage ¶
UseLanguage names the language the inflector works in.
English is the only language this package carries rules for, so it is the only one accepted, and anything else returns ErrLanguageNotSupported. Plural and Singular would otherwise keep answering in English under another language's name, which is worse than refusing.
func WordCount ¶
WordCount counts the words in the string, where a word is a run of letters and of the extra characters given.
An apostrophe and a hyphen are part of a word but cannot open one -- and a hyphen cannot close the string -- unless the caller names them in characters. Letters are the ASCII ones, because the counting reads bytes.
func WordWrap ¶
WordWrap breaks the string into lines of at most the given number of characters, breaking at spaces and writing brk where it breaks; a word longer than the line is left whole unless cutLongWords is set.
It counts bytes rather than characters, and treats an occurrence of brk already in the string as a line that has ended. A width of zero or less returns the string untouched.
Types ¶
type Stringable ¶
type Stringable struct {
// contains filtered or unexported fields
}
Stringable is a string carried through a chain of the transformations in this package, where every step that produces a string produces another Stringable.
str.Of(" Purchase Order ").Trim().Snake("_").ToString() // "purchase_order"
It is a value, not a handle: every method returns a new Stringable and none of them changes the one it was called on, so a Stringable can be kept, passed and reused without anyone else's chain reaching it.
The methods that end a chain -- Length, Contains, ToString and the rest -- return the Go type the answer is, not a Stringable.
func Of ¶
func Of(value string) Stringable
Of wraps a string as a Stringable, which is where a chain begins.
func (Stringable) ASCII ¶
func (s Stringable) ASCII() Stringable
ASCII folds the string to ASCII, dropping the runes the fold table cannot spell; see the comment on ASCII.
func (Stringable) After ¶
func (s Stringable) After(search string) Stringable
After is everything past the first occurrence of search.
func (Stringable) AfterLast ¶
func (s Stringable) AfterLast(search string) Stringable
AfterLast is everything past the last occurrence of search.
func (Stringable) Apa ¶
func (s Stringable) Apa() Stringable
Apa converts the string to APA-style title case.
func (Stringable) Append ¶
func (s Stringable) Append(values ...string) Stringable
Append puts the values on the end, in order.
func (Stringable) Basename ¶
func (s Stringable) Basename(suffix ...string) Stringable
Basename is the last component of a path, with the suffix removed when one is given and the component is more than the suffix itself.
func (Stringable) Before ¶
func (s Stringable) Before(search string) Stringable
Before is everything up to the first occurrence of search.
func (Stringable) BeforeLast ¶
func (s Stringable) BeforeLast(search string) Stringable
BeforeLast is everything up to the last occurrence of search.
func (Stringable) Between ¶
func (s Stringable) Between(from, to string) Stringable
Between is the largest portion sitting after the first from and before the last to.
func (Stringable) BetweenFirst ¶
func (s Stringable) BetweenFirst(from, to string) Stringable
BetweenFirst is the smallest portion sitting after the first from and before the first to.
func (Stringable) Camel ¶
func (s Stringable) Camel() Stringable
Camel converts the string to camel case.
func (Stringable) CharAt ¶
func (s Stringable) CharAt(index int) (string, bool)
CharAt is the character at the given index, counting back from the end when the index is negative. The second result is false for an index outside the string.
func (Stringable) ChopEnd ¶
func (s Stringable) ChopEnd(needle ...string) Stringable
ChopEnd removes the first of the given needles that the string ends with.
func (Stringable) ChopStart ¶
func (s Stringable) ChopStart(needle ...string) Stringable
ChopStart removes the first of the given needles that the string starts with.
func (Stringable) ClassBasename ¶
func (s Stringable) ClassBasename() Stringable
ClassBasename is the part of a fully qualified class name after the last namespace separator, which is read as either a backslash or a slash.
func (Stringable) Contains ¶
func (s Stringable) Contains(needles []string, ignoreCase bool) bool
Contains reports whether the string holds any one of the needles.
func (Stringable) ContainsAll ¶
func (s Stringable) ContainsAll(needles []string, ignoreCase bool) bool
ContainsAll reports whether the string holds every one of the needles.
func (Stringable) ConvertCase ¶
func (s Stringable) ConvertCase(mode int) Stringable
ConvertCase converts the string in the given mode, which is one of CaseUpper, CaseLower, CaseTitle or CaseFold.
func (Stringable) Counted ¶
func (s Stringable) Counted(count int) Stringable
Counted is the count and the noun agreeing with it.
func (Stringable) Deduplicate ¶
func (s Stringable) Deduplicate(character ...string) Stringable
Deduplicate collapses a run of the given character to one occurrence of it; passing none deduplicates spaces.
func (Stringable) Dirname ¶
func (s Stringable) Dirname(levels ...int) Stringable
Dirname is the path with its last component removed, levels times over; passing none removes one.
func (Stringable) DoesntContain ¶
func (s Stringable) DoesntContain(needles []string, ignoreCase bool) bool
DoesntContain is Contains negated.
func (Stringable) DoesntEndWith ¶
func (s Stringable) DoesntEndWith(needles ...string) bool
DoesntEndWith is EndsWith negated.
func (Stringable) DoesntStartWith ¶
func (s Stringable) DoesntStartWith(needles ...string) bool
DoesntStartWith is StartsWith negated.
func (Stringable) Dump ¶
func (s Stringable) Dump(args ...any) Stringable
Dump writes the value out and returns the Stringable so a chain carries on through it.
func (Stringable) EndsWith ¶
func (s Stringable) EndsWith(needles ...string) bool
EndsWith reports whether the string ends with any one of the needles.
func (Stringable) Exactly ¶
func (s Stringable) Exactly(value string) bool
Exactly reports whether the string equals value.
func (Stringable) Excerpt ¶
Excerpt cuts an excerpt out of the string around the first case-insensitive occurrence of phrase, keeping radius characters on each side and marking a cut end with omission. The second result is false when the phrase is not there.
func (Stringable) Explode ¶
func (s Stringable) Explode(delimiter string, limit ...int) []string
Explode splits the string on the delimiter, and returns nothing when the delimiter is empty.
A positive limit leaves the rest of the string in the last piece, a negative one drops that many pieces off the end, and zero is read as one.
func (Stringable) Finish ¶
func (s Stringable) Finish(cap string) Stringable
Finish caps the string with a single instance of cap.
func (Stringable) FromBase64 ¶
func (s Stringable) FromBase64(strict bool) Stringable
FromBase64 decodes standard base64. What does not decode becomes the empty string.
func (Stringable) Headline ¶
func (s Stringable) Headline() Stringable
Headline converts the string to a title-cased sentence.
func (Stringable) Initials ¶
func (s Stringable) Initials(capitalize bool) Stringable
Initials keeps the first character of every whitespace-separated part.
func (Stringable) InlineMarkdown ¶
func (s Stringable) InlineMarkdown() Stringable
InlineMarkdown renders only the inline part of the string as HTML.
func (Stringable) Is ¶
func (s Stringable) Is(pattern []string, ignoreCase bool) bool
Is reports whether the string matches any one of the patterns, where * stands for any run of characters, including none.
func (Stringable) IsASCII ¶
func (s Stringable) IsASCII() bool
IsASCII reports whether every byte of the string is below 128.
func (Stringable) IsEmpty ¶
func (s Stringable) IsEmpty() bool
IsEmpty reports whether the string is empty.
func (Stringable) IsJSON ¶
func (s Stringable) IsJSON() bool
IsJSON reports whether the string parses as JSON.
func (Stringable) IsMatch ¶
func (s Stringable) IsMatch(patterns []*regexp.Regexp) bool
IsMatch reports whether the string matches any one of the patterns.
func (Stringable) IsULID ¶
func (s Stringable) IsULID() bool
IsULID reports whether the string has the shape of a ULID.
func (Stringable) IsURL ¶
func (s Stringable) IsURL(protocols ...string) bool
IsURL reports whether the string is an absolute URL whose scheme is one of the protocols given.
func (Stringable) IsUUID ¶
func (s Stringable) IsUUID() bool
IsUUID reports whether the string has the shape of a hyphenated UUID.
func (Stringable) Kebab ¶
func (s Stringable) Kebab() Stringable
Kebab converts the string to kebab case.
func (Stringable) Lcfirst ¶
func (s Stringable) Lcfirst() Stringable
Lcfirst lowercases the first character and leaves the rest alone.
func (Stringable) Length ¶
func (s Stringable) Length() int
Length is the number of characters in the string, not the number of bytes.
func (Stringable) Limit ¶
func (s Stringable) Limit(limit int, end string, preserveWords bool) Stringable
Limit cuts the string to at most limit display columns and appends end when it had to cut.
func (Stringable) Ltrim ¶
func (s Stringable) Ltrim(characters ...string) Stringable
Ltrim is Trim on the left side only.
func (Stringable) Markdown ¶
func (s Stringable) Markdown() Stringable
Markdown renders the string as HTML.
func (Stringable) Mask ¶
func (s Stringable) Mask(character string, index int, length ...int) Stringable
Mask replaces a run of the string, starting at index, with the first character of character repeated.
func (Stringable) Match ¶
func (s Stringable) Match(pattern *regexp.Regexp) Stringable
Match is the first capture group of the first match, or the whole match when the pattern captures nothing.
func (Stringable) MatchAll ¶
func (s Stringable) MatchAll(pattern *regexp.Regexp) []string
MatchAll is the first capture group of every match, or every whole match when the pattern captures nothing.
func (Stringable) NewLine ¶
func (s Stringable) NewLine(count ...int) Stringable
NewLine appends count line breaks; passing none appends one.
The break is "\n" on every platform.
func (Stringable) Numbers ¶
func (s Stringable) Numbers() Stringable
Numbers keeps the digits of the string and drops everything else.
func (Stringable) PadBoth ¶
func (s Stringable) PadBoth(length int, pad ...string) Stringable
PadBoth grows the string to the given number of characters, splitting the padding between the two ends.
func (Stringable) PadLeft ¶
func (s Stringable) PadLeft(length int, pad ...string) Stringable
PadLeft grows the string to the given number of characters by putting pad in front of it.
func (Stringable) PadRight ¶
func (s Stringable) PadRight(length int, pad ...string) Stringable
PadRight grows the string to the given number of characters by putting pad behind it.
func (Stringable) ParseCallback ¶
func (s Stringable) ParseCallback(fallback string) (string, string)
ParseCallback splits a "Class@method" string into its two halves, and answers the whole string with the fallback when there is no at sign in it.
func (Stringable) Pascal ¶
func (s Stringable) Pascal() Stringable
Pascal converts the string to Pascal case. It is Studly under the other name.
func (Stringable) Pipe ¶
func (s Stringable) Pipe(callback func(Stringable) string) Stringable
Pipe hands the Stringable to the callback and wraps what comes back.
func (Stringable) Plural ¶
func (s Stringable) Plural(count ...int) Stringable
Plural is the plural of the English noun the string holds.
func (Stringable) PluralPascal ¶
func (s Stringable) PluralPascal(count ...int) Stringable
PluralPascal pluralizes the last word of a Pascal case string. It is PluralStudly under the other name.
func (Stringable) PluralStudly ¶
func (s Stringable) PluralStudly(count ...int) Stringable
PluralStudly pluralizes the last word of a studly caps string and leaves everything in front of it alone.
func (Stringable) Position ¶
func (s Stringable) Position(needle string, offset int) int
Position is the character index of the first occurrence of needle at or after offset, and -1 when the needle is absent.
func (Stringable) Prepend ¶
func (s Stringable) Prepend(values ...string) Stringable
Prepend puts the values on the front, in order.
func (Stringable) Remove ¶
func (s Stringable) Remove(search []string, caseSensitive bool) Stringable
Remove deletes every occurrence of each search from the string.
func (Stringable) Repeat ¶
func (s Stringable) Repeat(times int) Stringable
Repeat is the string written times over.
func (Stringable) Replace ¶
func (s Stringable) Replace(search, replace []string, caseSensitive bool) Stringable
Replace replaces every occurrence of each search with the replacement standing at the same index.
func (Stringable) ReplaceArray ¶
func (s Stringable) ReplaceArray(search string, replace []string) Stringable
ReplaceArray walks the occurrences of search from left to right and spends one replacement on each.
func (Stringable) ReplaceEnd ¶
func (s Stringable) ReplaceEnd(search, replace string) Stringable
ReplaceEnd replaces search only where it ends the string.
func (Stringable) ReplaceFirst ¶
func (s Stringable) ReplaceFirst(search, replace string) Stringable
ReplaceFirst replaces the first occurrence of search.
func (Stringable) ReplaceLast ¶
func (s Stringable) ReplaceLast(search, replace string) Stringable
ReplaceLast replaces the last occurrence of search.
func (Stringable) ReplaceMatches ¶
func (s Stringable) ReplaceMatches(pattern *regexp.Regexp, replace string, limit int) Stringable
ReplaceMatches replaces at most limit matches of the pattern, and every one of them when limit is negative.
func (Stringable) ReplaceStart ¶
func (s Stringable) ReplaceStart(search, replace string) Stringable
ReplaceStart replaces search only where it begins the string.
func (Stringable) Reverse ¶
func (s Stringable) Reverse() Stringable
Reverse reverses the string character by character.
func (Stringable) Rtrim ¶
func (s Stringable) Rtrim(characters ...string) Stringable
Rtrim is Trim on the right side only.
func (Stringable) Scan ¶
func (s Stringable) Scan(format string) []string
Scan reads the fields a format names out of the string.
The format takes %s for a run of non-space characters, %d for an integer, %f for a decimal, %c for one character, %% for a literal per cent, whitespace for any run of whitespace, and anything else for itself. A field that does not match ends the scan, and what was read up to there is the answer.
func (Stringable) Singular ¶
func (s Stringable) Singular() Stringable
Singular is the singular of the English noun the string holds.
func (Stringable) Slug ¶
func (s Stringable) Slug(separator string) Stringable
Slug is the string as an address, with separator between the words.
func (Stringable) Snake ¶
func (s Stringable) Snake(delimiter string) Stringable
Snake converts the string to snake case with the given delimiter.
func (Stringable) Split ¶
func (s Stringable) Split(pattern any, limit ...int) []string
Split cuts the string into pieces. An int pattern makes pieces that many characters wide, and a *regexp.Regexp or a string splits on the matches; anything else returns nothing.
The optional limit is the greatest number of pieces to produce, and a value below one means no limit.
func (Stringable) Squish ¶
func (s Stringable) Squish() Stringable
Squish trims both ends and collapses every run of whitespace inside the string to a single space.
func (Stringable) Start ¶
func (s Stringable) Start(prefix string) Stringable
Start begins the string with a single instance of prefix.
func (Stringable) StartsWith ¶
func (s Stringable) StartsWith(needles ...string) bool
StartsWith reports whether the string begins with any one of the needles.
func (Stringable) String ¶
func (s Stringable) String() string
String is the string itself. It makes Stringable an fmt.Stringer, which is what makes a Stringable print as its own text.
func (Stringable) StripTags ¶
func (s Stringable) StripTags() Stringable
StripTags removes everything between an opening angle bracket and the next closing one. No tag is allowed through.
func (Stringable) Studly ¶
func (s Stringable) Studly() Stringable
Studly converts the string to studly caps.
func (Stringable) Substr ¶
func (s Stringable) Substr(start int, length ...int) Stringable
Substr is the portion of the string given by start and length, counted in characters.
func (Stringable) SubstrCount ¶
func (s Stringable) SubstrCount(needle string, offset int, length ...int) int
SubstrCount counts the non-overlapping occurrences of needle from offset onwards, in bytes.
func (Stringable) SubstrReplace ¶
func (s Stringable) SubstrReplace(replace string, offset int, length ...int) Stringable
SubstrReplace replaces the portion of the string given by offset and length, in bytes.
func (Stringable) Swap ¶
func (s Stringable) Swap(swap map[string]string) Stringable
Swap applies a whole map of replacements in one left-to-right pass, so nothing a replacement produces is replaced again.
func (Stringable) Take ¶
func (s Stringable) Take(limit int) Stringable
Take is the first limit characters of the string, or the last limit characters when limit is negative.
func (Stringable) Tap ¶
func (s Stringable) Tap(callback func(Stringable)) Stringable
Tap hands the Stringable to the callback and returns it unchanged.
func (Stringable) Test ¶
func (s Stringable) Test(patterns []*regexp.Regexp) bool
Test is IsMatch under the other name.
func (Stringable) Title ¶
func (s Stringable) Title() Stringable
Title uppercases the first letter of every word and lowercases the rest of each one.
func (Stringable) ToBase64 ¶
func (s Stringable) ToBase64() Stringable
ToBase64 encodes the string as standard base64 with padding.
func (Stringable) ToBoolean ¶
func (s Stringable) ToBoolean() bool
ToBoolean reads the string as a boolean: "1", "true", "on" and "yes" are true, in any case and with the ends trimmed, and everything else is false.
func (Stringable) ToDate ¶
func (s Stringable) ToDate(format ...string) (time.Time, error)
ToDate reads the string as a time.
With a format, the format is written in single-letter tokens -- "Y-m-d H:i:s" and the like -- and the string has to match it whole. With none it tries the layouts a machine writes, in turn, and a string none of them reads is an error.
A layout that carries no zone is read as UTC, and a caller that wants another one converts what comes back.
func (Stringable) ToFloat ¶
func (s Stringable) ToFloat() float64
ToFloat reads the longest decimal at the front of the string and answers zero when there is none.
func (Stringable) ToInteger ¶
func (s Stringable) ToInteger(base ...int) int
ToInteger reads the longest integer at the front of the string and answers zero when there is none.
The optional base defaults to ten. Base zero reads the prefix -- 0x for hexadecimal, 0b for binary, 0 for octal.
func (Stringable) Transliterate ¶
func (s Stringable) Transliterate(unknown string, strict bool) Stringable
Transliterate writes the string in ASCII, putting unknown in the place of every rune it has no ASCII spelling for.
func (Stringable) Trim ¶
func (s Stringable) Trim(characters ...string) Stringable
Trim removes the given characters from both ends; passing none removes whitespace and the invisible marks.
func (Stringable) Ucfirst ¶
func (s Stringable) Ucfirst() Stringable
Ucfirst uppercases the first character and leaves the rest alone.
func (Stringable) Ucsplit ¶
func (s Stringable) Ucsplit() []string
Ucsplit splits the string in front of every uppercase letter, dropping the empty pieces.
func (Stringable) Ucwords ¶
func (s Stringable) Ucwords(separators ...string) Stringable
Ucwords uppercases the first letter of the string and every lowercase letter that follows one of the separators; passing none uses space, tab and the line breaks.
func (Stringable) Unless ¶
func (s Stringable) Unless(condition bool, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
Unless is When with the condition read the other way.
func (Stringable) Unwrap ¶
func (s Stringable) Unwrap(before string, after ...string) Stringable
Unwrap removes before from the front of the string and after from the back, each only if it is there; passing no after repeats before.
func (Stringable) Value ¶
func (s Stringable) Value() string
Value is the string itself. It is ToString under the other name.
func (Stringable) When ¶
func (s Stringable) When(condition bool, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
When runs the callback when the condition holds, and the optional second callback when it does not, and hands back whatever comes out.
func (Stringable) WhenContains ¶
func (s Stringable) WhenContains(needles []string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenContains is When on whether the string holds any one of the needles.
func (Stringable) WhenContainsAll ¶
func (s Stringable) WhenContainsAll(needles []string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenContainsAll is When on whether the string holds every one of the needles.
func (Stringable) WhenDoesntEndWith ¶
func (s Stringable) WhenDoesntEndWith(needles []string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenDoesntEndWith is When on whether the string ends with none of the needles.
func (Stringable) WhenDoesntStartWith ¶
func (s Stringable) WhenDoesntStartWith(needles []string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenDoesntStartWith is When on whether the string begins with none of the needles.
func (Stringable) WhenEmpty ¶
func (s Stringable) WhenEmpty(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenEmpty is When on whether the string is empty.
func (Stringable) WhenEndsWith ¶
func (s Stringable) WhenEndsWith(needles []string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenEndsWith is When on whether the string ends with any one of the needles.
func (Stringable) WhenExactly ¶
func (s Stringable) WhenExactly(value string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenExactly is When on whether the string equals value.
func (Stringable) WhenIs ¶
func (s Stringable) WhenIs(pattern []string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenIs is When on whether the string matches any one of the glob patterns.
func (Stringable) WhenIsASCII ¶
func (s Stringable) WhenIsASCII(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenIsASCII is When on whether every byte of the string is below 128.
func (Stringable) WhenIsULID ¶
func (s Stringable) WhenIsULID(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenIsULID is When on whether the string has the shape of a ULID.
func (Stringable) WhenIsUUID ¶
func (s Stringable) WhenIsUUID(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenIsUUID is When on whether the string has the shape of a UUID.
func (Stringable) WhenNotEmpty ¶
func (s Stringable) WhenNotEmpty(callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenNotEmpty is When on whether the string is not empty.
func (Stringable) WhenNotExactly ¶
func (s Stringable) WhenNotExactly(value string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenNotExactly is When on whether the string does not equal value.
func (Stringable) WhenStartsWith ¶
func (s Stringable) WhenStartsWith(needles []string, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenStartsWith is When on whether the string begins with any one of the needles.
func (Stringable) WhenTest ¶
func (s Stringable) WhenTest(patterns []*regexp.Regexp, callback func(Stringable) Stringable, otherwise ...func(Stringable) Stringable) Stringable
WhenTest is When on whether the string matches any one of the regular expressions.
func (Stringable) WordCount ¶
func (s Stringable) WordCount(characters ...string) int
WordCount counts the words in the string, where a word is a run of letters and of the extra characters given.
func (Stringable) WordWrap ¶
func (s Stringable) WordWrap(characters int, brk string, cutLongWords bool) Stringable
WordWrap breaks the string into lines of at most the given number of characters, writing brk where it breaks.
func (Stringable) Words ¶
func (s Stringable) Words(words int, end string) Stringable
Words cuts the string to at most words words and appends end when it had to cut.
func (Stringable) Wrap ¶
func (s Stringable) Wrap(before string, after ...string) Stringable
Wrap puts before in front of the string and after behind it; passing no after repeats before.