Documentation
¶
Overview ¶
Package str provides utility functions for string manipulation.
Index ¶
- func After(s, search string) string
- func AfterLast(s, search string) string
- func Apa(s string) string
- func Ascii(s string) string
- func Before(s, search string) string
- func BeforeLast(s, search string) string
- func Between(s, start, end string) string
- func BetweenFirst(s, start, end string) string
- func CamelCase(s string) string
- func Capitalize(s string) string
- func CharAt(s string, position int) string
- func ChopEnd(s string, suffixes interface{}) string
- func ChopStart(s string, prefixes interface{}) string
- func Contains(s, substr string) bool
- func ContainsAll(s string, substrings ...string) bool
- func ContainsAny(s string, substrings ...string) bool
- func Count(s, substr string) int
- func CountWords(s string) int
- func DoesntContain(s string, substrings interface{}) bool
- func Ellipsis(s string, length int) string
- func EndsWith(s string, substrings ...string) bool
- func Excerpt(s, phrase string, options ...ExcerptOptions) string
- func Finish(s, cap string) string
- func FormatWithCommas(n int64) string
- func Headline(s string) string
- func Index(s, substr string) int
- func Is(pattern, s string) bool
- func IsAscii(s string) bool
- func IsEmptyOrWhitespace(s string) bool
- func IsJson(s string) bool
- func Join(arr []string, separator string) string
- func KebabCase(s string) string
- func LastIndex(s, substr string) int
- func Lcfirst(s string) string
- func Length(str string) int
- func Limit(s string, limit int, options ...string) string
- func Ltrim(s, chars string) string
- func Mask(s string, startVisible, endVisible int, maskChar rune) string
- func Match(pattern, s string) string
- func MatchAll(pattern, s string) []string
- func OnlyAlphanumeric(s string) string
- func PadLeft(s string, padChar rune, length int) string
- func PadRight(s string, padChar rune, length int) string
- func PascalCase(s string) string
- func Password(length ...int) string
- func Plural(s string) string
- func Random(length int) string
- func Remove(search, subject string, options ...bool) string
- func Repeat(s string, n int) string
- func Replace(search, replace, subject string) string
- func ReplaceArray(search string, replace []string, subject string) string
- func ReplaceFirst(search, replace, subject string) string
- func ReplaceLast(search, replace, subject string) string
- func ReplaceMatches(pattern string, replace interface{}, subject string) string
- func Reverse(s string) string
- func Rtrim(s, chars string) string
- func Singular(s string) string
- func Slugify(s string) string
- func SnakeCase(s string) string
- func Split(s, separator string) []string
- func Squish(s string) string
- func Start(s, prefix string) string
- func StartsWith(s string, substrings ...string) bool
- func Studly(s string) string
- func Substr(s string, start, length int) string
- func Swap(replacements map[string]string, subject string) string
- func ToLower(s string) string
- func ToString[T any](value T) string
- func ToTitleCase(s string) string
- func ToUpper(s string) string
- func Trim(s string, cutset ...string) string
- func TrimEnd(s string, cutset ...string) string
- func TrimStart(s string, cutset ...string) string
- func Truncate(s string, maxLength int) string
- func TruncateWords(s string, maxWords int) string
- func Ucfirst(s string) string
- func WordAt(s string, position int) string
- func Words(str string) []string
- func WordsPattern(s, pattern string) []string
- func Wordwrap(s string, width int, breakChar string) string
- type ExcerptOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func After ¶ added in v1.1.0
After returns the portion of a string after the first occurrence of a given value.
Parameters:
- s: The string to search in
- search: The substring to search for
Returns:
- string: Everything after the search string, or the entire string if not found
Example:
After("hello world", "hello ") -> "world" After("hello world", "not found") -> "hello world" After("hello world", "") -> "hello world"
func AfterLast ¶ added in v1.1.0
AfterLast returns the portion of a string after the last occurrence of a given value.
Parameters:
- s: The string to search in
- search: The substring to search for
Returns:
- string: Everything after the last occurrence of search string, or entire string if not found
Example:
AfterLast("hello/world/test", "/") -> "test" AfterLast("hello world hello", "hello ") -> "hello" AfterLast("hello world", "not found") -> "hello world" AfterLast("hello world", "") -> "hello world"
func Apa ¶ added in v1.1.0
Apa converts a string to title case but with the first word having only its first letter capitalized. This is similar to AP (Associated Press) style for article titles.
Refer:
https://en.wikipedia.org/wiki/AP_style https://en.wikipedia.org/wiki/Title_case#AP_style https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case
Parameters:
- s: The string to convert
Returns:
- string: The converted string
Example:
Apa("Creating A Project") -> "Creating a Project" Apa("HELLO WORLD") -> "Hello WORLD" Apa("hello WORLD") -> "Hello WORLD" Apa("") -> ""
func Ascii ¶ added in v1.1.0
Ascii transliterates non-ASCII characters to their ASCII equivalents.
Parameters:
- s: The string to transliterate
Returns:
- string: The transliterated string with only ASCII characters
Example:
Ascii("û") -> "u" Ascii("café") -> "cafe" Ascii("über") -> "uber" Ascii("Crème Brûlée") -> "Creme Brulee"
func Before ¶ added in v1.1.0
Before returns the portion of a string before the first occurrence of a given value.
Parameters:
- s: The string to search in
- search: The substring to search for
Returns:
- string: Everything before the search string, or the entire string if not found
Example:
Before("hello world", " world") -> "hello" Before("hello/world/test", "/") -> "hello" Before("hello world", "not found") -> "hello world" Before("hello world", "") -> "hello world"
func BeforeLast ¶ added in v1.1.0
BeforeLast returns the portion of a string before the last occurrence of a given value.
Parameters:
- s: The string to search in
- search: The substring to search for
Returns:
- string: Everything before the last occurrence of search string, or entire string if not found
Example:
BeforeLast("hello/world/test", "/") -> "hello/world" BeforeLast("hello world hello", "hello") -> "hello world " BeforeLast("hello world", "not found") -> "hello world" BeforeLast("hello world", "") -> "hello world"
func Between ¶ added in v1.1.0
Between returns the portion of a string between two values.
Parameters:
- s: The string to search in
- start: The starting substring
- end: The ending substring
Returns:
- string: The portion between start and end strings, or entire string if not found
Example:
Between("hello [world] test", "[", "]") -> "world" Between("<div>content</div>", "<div>", "</div>") -> "content" Between("hello world", "[", "]") -> "hello world" Between("hello world", "", "]") -> "hello world" Between("hello world", "[", "") -> "hello world" Between("hello [[world]]", "[", "]") -> "world"
func BetweenFirst ¶ added in v1.1.0
BetweenFirst returns the portion of a string between the first occurrence of two strings.
Parameters:
- s: The string to search in
- start: The starting delimiter
- end: The ending delimiter
Returns:
- string: The portion between the first occurrence of start and end strings, or entire string if not found
Example:
BetweenFirst("[a] bc [d]", "[", "]") -> "a" BetweenFirst("<div>content</div>", "<div>", "</div>") -> "content" BetweenFirst("hello world", "[", "]") -> "hello world" BetweenFirst("hello world", "", "]") -> "hello world" BetweenFirst("hello world", "[", "") -> "hello world"
func CamelCase ¶ added in v1.1.0
CamelCase converts a string to camelCase format. It splits the string into words, converts the first word to lowercase, and capitalizes the first letter of each subsequent word with no separators.
Parameters:
- s: The string to convert to camelCase
Returns:
- string: The camelCase formatted string
Example:
CamelCase("foo bar") -> "fooBar" CamelCase("Foo Bar") -> "fooBar" CamelCase("foo bar baz") -> "fooBarBaz" CamelCase("") -> ""
func Capitalize ¶
Capitalize capitalizes the first character of a string. It leaves the rest of the string unchanged. If the string is empty, it returns an empty string.
Parameters:
- s: The string to capitalize
Returns:
- string: The string with first character capitalized
Example:
Capitalize("fred") -> "Fred" Capitalize("FRED") -> "FRED" Capitalize("fred flintstone") -> "Fred flintstone" Capitalize("") -> ""
func CharAt ¶ added in v1.1.0
CharAt returns the character at the specified position in a string.
Parameters:
- s: The input string.
- position: The position of the character to return (0-indexed).
Returns:
- string: The character at the specified position, or an empty string if the position is out of bounds.
Example:
CharAt("This is my name.", 6) -> "s" CharAt("Hello", 0) -> "H" CharAt("Hello", 4) -> "o" CharAt("Hello", 5) -> "" (position out of bounds) CharAt("", 0) -> "" (empty string)
func ChopEnd ¶ added in v1.1.0
ChopEnd removes a suffix from a string if it exists. If an array of suffixes is provided, it will remove the first matching suffix.
Parameters:
- s: The string to process
- suffixes: The suffix or array of suffixes to remove
Returns:
- string: The string with the suffix removed
Example:
ChopEnd("app/Models/Photograph.php", ".php") -> "app/Models/Photograph" ChopEnd("laravel.com/index.php", []string{"/index.html", "/index.php"}) -> "laravel.com" ChopEnd("laravel.com", ".php") -> "laravel.com" (no suffix to remove) ChopEnd("", ".php") -> "" (empty string)
func ChopStart ¶ added in v1.1.0
ChopStart removes a prefix from a string if it exists. If an array of prefixes is provided, it will remove the first matching prefix.
Parameters:
- s: The string to process
- prefixes: The prefix or array of prefixes to remove
Returns:
- string: The string with the prefix removed
Example:
ChopStart("https://laravel.com", "https://") -> "laravel.com" ChopStart("http://laravel.com", []string{"https://", "http://"}) -> "laravel.com" ChopStart("laravel.com", "https://") -> "laravel.com" (no prefix to remove) ChopStart("", "https://") -> "" (empty string)
func Contains ¶
Contains determines if a string contains a given substring.
Parameters:
- s: The string to search in
- substr: The substring to search for
Returns:
- bool: True if substring is found, false otherwise
Example:
Contains("abc", "b") -> true Contains("abc", "d") -> false Contains("abc", "") -> true Contains("", "") -> true
func ContainsAll ¶ added in v1.1.0
ContainsAll determines if a string contains all of the given substrings.
Parameters:
- s: The string to search in
- substrings: Variable number of substrings to search for
Returns:
- bool: True if all substrings are found, false otherwise
Example:
ContainsAll("hello world", "hello", "world") -> true ContainsAll("hello world", "hello", "missing") -> false ContainsAll("hello world", "HELLO", "WORLD") -> false (case-sensitive) ContainsAll("hello world") -> true (no substrings to check)
func ContainsAny ¶ added in v1.1.0
ContainsAny checks if a string contains any of the specified substrings.
Parameters:
- s: The string to search in
- substrings: Variable number of substrings to search for
Returns:
- bool: True if the string contains any of the substrings, false otherwise
Example:
ContainsAny("hello world", "hello", "hi") -> true ContainsAny("hello world", "hi", "hey") -> false ContainsAny("hello world", "world") -> true ContainsAny("hello world", "") -> true
func Count ¶
Count counts the occurrences of a substring in a string.
Parameters:
- s: The string to search in
- substr: The substring to count occurrences of
Returns:
- int: The number of non-overlapping occurrences of the substring
Example:
Count("ababab", "ab") -> 3 Count("aaa", "a") -> 3 Count("abc", "d") -> 0 Count("", "a") -> 0
func CountWords ¶ added in v1.1.0
CountWords counts the number of words in a string. Words are considered to be separated by whitespace.
Parameters:
- s: The string to count words in
Returns:
- int: The number of words in the string
Example:
CountWords("hello world") -> 2 CountWords("hello world") -> 2 CountWords("") -> 0 CountWords(" ") -> 0 CountWords("hello") -> 1
func DoesntContain ¶ added in v1.1.0
DoesntContain determines if a string does not contain a specific substring or any of the substrings in an array.
Parameters:
- s: The string to check
- substrings: The substring(s) to check for
Returns:
- bool: True if the string doesn't contain the specified substring(s), false otherwise
Example:
DoesntContain("This is name", "my") -> true DoesntContain("This is name", []string{"my", "foo"}) -> true DoesntContain("This is my name", "my") -> false DoesntContain("This is my name", []string{"my", "foo"}) -> false
func Ellipsis ¶
Ellipsis trims and truncates a string to a specified length in bytes and appends an ellipsis if truncated. It ensures that UTF-8 characters are not split in the middle.
Parameters:
- s: The string to truncate
- length: The maximum length in bytes before truncation
Returns:
- string: The truncated string with "..." appended if truncation occurred
Example:
Ellipsis("Hello, 世界", 8) -> "Hello, ..." Ellipsis("Hello", 10) -> "Hello" Ellipsis("你好, World", 6) -> "你好..." Ellipsis("Hello", 0) -> "..."
func EndsWith ¶
EndsWith determines if a string ends with any of the given substrings. It checks each substring and returns true as soon as it finds a match.
Parameters:
- s: The string to check
- substrings: One or more substrings to check for at the end of the string
Returns:
- bool: True if the string ends with any of the given substrings, false otherwise
Example:
EndsWith("abc", "c") -> true EndsWith("abc", "bc") -> true EndsWith("abc", "abc") -> true EndsWith("abc", "d") -> false EndsWith("abc", "a", "b", "c") -> true EndsWith("", "") -> true
func Excerpt ¶ added in v1.1.0
func Excerpt(s, phrase string, options ...ExcerptOptions) string
Excerpt extracts a portion of text around a given phrase. It returns a substring that includes the phrase and a certain number of characters around it. If the excerpt doesn't include the entire string, omission text is added at the beginning and/or end.
Parameters:
- s: The string to excerpt
- phrase: The phrase to search for
- options: Optional ExcerptOptions struct containing: radius: The number of characters to include around the phrase (default: 100) omission: The text to use for omission (default: "...")
Returns:
- string: The excerpted string with omission text if truncated
Example:
Excerpt("This is my name", "my", ExcerptOptions{Radius: 3}) -> "...is my na..." Excerpt("This is my name", "my", ExcerptOptions{Radius: 5, Omission: "(...)"}) -> "(...)is my name" Excerpt("This is my name", "foo", ExcerptOptions{}) -> "This is my name" Excerpt("", "foo", ExcerptOptions{}) -> ""
func Finish ¶ added in v1.1.0
Finish appends a single instance of the given value to a string if it does not already end with it.
Parameters:
- s: The string to append to
- cap: The string to append
Returns:
- string: The resulting string
Example:
Finish("hello", "!") -> "hello!" Finish("hello!", "!") -> "hello!" (already ends with the cap) Finish("hello", " world") -> "hello world" Finish("", "hello") -> "hello"
func FormatWithCommas ¶ added in v1.1.0
FormatWithCommas formats a number as a string with commas as thousand separators. Note: The current implementation does not actually add commas and simply returns the string representation of the number. This function may be updated in the future.
Parameters:
- n: The number to format
Returns:
- string: The formatted number string
Example:
FormatWithCommas(1000) -> "1000" FormatWithCommas(1234567) -> "1234567" FormatWithCommas(-1000) -> "-1000"
func Headline ¶ added in v1.1.0
Headline converts a string to Title Case with spaces between words. It splits the string into words, capitalizes each word, and joins them with spaces. This function handles various word boundaries including camelCase, snake_case, and kebab-case.
Parameters:
- s: The string to convert to headline format
Returns:
- string: The headline formatted string with each word capitalized and separated by spaces
Example:
Headline("steve_jobs") -> "Steve Jobs" Headline("EmailNotificationSent") -> "Email Notification Sent" Headline("hello-world") -> "Hello World"
func Index ¶
Index returns the index of the first occurrence of a substring in a string. Returns -1 if the substring is not found.
Parameters:
- s: The string to search in
- substr: The substring to search for
Returns:
- int: The index of the first occurrence of substr in s, or -1 if not found
Example:
Index("abc", "b") -> 1 Index("abcabc", "c") -> 2 Index("abc", "d") -> -1 Index("", "a") -> -1
func Is ¶ added in v1.1.0
Is determines if a string matches a given pattern. Asterisks may be used as wildcard values.
Parameters:
- pattern: The pattern to match against (can include * wildcards)
- s: The string to check
Returns:
- bool: True if string matches pattern, false otherwise
Example:
Is("foo*", "foobar") -> true Is("*bar", "foobar") -> true Is("foo*bar", "foobar") -> true Is("foo", "foobar") -> false Is("*baz", "foobar") -> false
func IsAscii ¶ added in v1.1.0
IsAscii determines if a string contains only 7-bit ASCII characters.
Parameters:
- s: The string to check
Returns:
- bool: True if string contains only ASCII characters, false otherwise
Example:
IsAscii("hello world") -> true IsAscii("hello123!@#") -> true IsAscii("こんにちは") -> false IsAscii("hello世界") -> false
func IsEmptyOrWhitespace ¶ added in v1.1.0
IsEmptyOrWhitespace checks if a string is empty or contains only whitespace characters.
Parameters:
- s: The string to check
Returns:
- bool: True if the string is empty or contains only whitespace, false otherwise
Example:
IsEmptyOrWhitespace("") -> true IsEmptyOrWhitespace(" ") -> true IsEmptyOrWhitespace("\t\n") -> true IsEmptyOrWhitespace("hello") -> false IsEmptyOrWhitespace(" hello ") -> false
func IsJson ¶ added in v1.1.0
IsJson determines if a string is valid JSON.
Parameters:
- s: The string to check
Returns:
- bool: True if the string is valid JSON, false otherwise
Example:
IsJson("[1,2,3]") -> true IsJson("{"first": "John", "last": "Doe"}") -> true IsJson("{first: "John", last: "Doe"}") -> false
func Join ¶
Join joins an array of strings with the given separator.
Parameters:
- arr: The array of strings to join
- separator: The separator to insert between elements
Returns:
- string: The joined string
Example:
Join([]string{"a", "b", "c"}, "-") -> "a-b-c" Join([]string{"a"}, "-") -> "a" Join([]string{}, "-") -> ""
func KebabCase ¶
KebabCase converts a string to kebab-case format. It splits the string into words, converts them to lowercase, and joins them with hyphens. Special characters are removed and multiple hyphens are replaced with a single hyphen.
Parameters:
- s: The string to convert to kebab-case
Returns:
- string: The kebab-case formatted string
Example:
KebabCase("hello world") -> "hello-world" KebabCase("HelloWorld") -> "hello-world" KebabCase("HELLO_WORLD") -> "hello-world"
func LastIndex ¶
LastIndex returns the index of the last occurrence of a substring in a string. Returns -1 if the substring is not found.
Parameters:
- s: The string to search in
- substr: The substring to search for
Returns:
- int: The index of the last occurrence of substr in s, or -1 if not found
Example:
LastIndex("abcabc", "b") -> 4 LastIndex("abcabc", "c") -> 5 LastIndex("abc", "d") -> -1 LastIndex("", "a") -> -1
func Lcfirst ¶ added in v1.1.0
Lcfirst converts the first character of a string to lowercase.
Parameters:
- s: The string to convert
Returns:
- string: The string with first character lowercased
Example:
Lcfirst("Hello") -> "hello" Lcfirst("Hello World") -> "hello World" Lcfirst("hello") -> "hello" (already lowercase) Lcfirst("") -> "" (empty string)
func Length ¶ added in v1.1.0
Length counts the number of Unicode characters (runes) in a string.
Parameters:
- str: The string to count runes in
Returns:
- int: The number of runes in the string
Example:
Length("Hello, 世界") -> 9 Length("abc") -> 3
func Limit ¶ added in v1.1.0
Limit truncates a string to the specified length.
Parameters:
- s: The string to truncate
- limit: Maximum length
Returns:
- string: The truncated string
Example:
Limit("hello world", 5) -> "hello" Limit("hello", 10) -> "hello" (no truncation needed) Limit("hello world", 0) -> "" (empty string) Limit("", 5) -> "" (empty input) Limit("Hello world", 5, "...") -> "Hello..."
func Ltrim ¶ added in v1.1.0
Ltrim removes specified characters from the start of a string.
Parameters:
- s: The string to trim
- chars: The characters to remove
Returns:
- string: The left-trimmed string
Example:
Ltrim(" hello", " ") -> "hello" Ltrim("xxxhello", "x") -> "hello" Ltrim("hello world", "hello ") -> "world" Ltrim("hello", "x") -> "hello" (no characters to trim) Ltrim("", "x") -> "" (empty string)
func Mask ¶ added in v1.1.0
Mask masks a portion of a string with the specified character. It leaves a specified number of characters visible at the beginning and end of the string.
Parameters:
- s: The string to mask
- startVisible: Number of characters to leave visible at start
- endVisible: Number of characters to leave visible at end
- maskChar: The character to use for masking
Returns:
- string: The masked string
Example:
Mask("1234567890", 4, 4, '*') -> "1234****90" Mask("1234567890", 2, 2, '#') -> "12######90" Mask("1234567890", 0, 4, '*') -> "******7890" Mask("1234", 2, 2, '*') -> "1234" (no masking if string is too short)
func Match ¶ added in v1.1.0
Match returns the first match of a regular expression pattern in a string. If the pattern contains capturing groups, it returns the first captured group. Otherwise, it returns the entire match.
Parameters:
- pattern: The regular expression pattern to match
- s: The string to search in
Returns:
- string: The matched portion or first captured group, or empty string if no match
Example:
Match("/bar/", "foo bar") -> "bar" Match("/foo (.*)/", "foo bar") -> "bar" Match("/xyz/", "foo bar") -> ""
func MatchAll ¶ added in v1.1.0
MatchAll returns all matches of a regular expression pattern in a string. If the pattern contains capturing groups, it returns all captured groups. Otherwise, it returns all full matches.
Parameters:
- pattern: The regular expression pattern to match
- s: The string to search in
Returns:
- []string: A slice containing all matches or captured groups, or an empty slice if no matches
Example:
MatchAll("/bar/", "bar foo bar") -> ["bar", "bar"] MatchAll("/f(\\w*)/", "bar fun bar fly") -> ["un", "ly"] MatchAll("/xyz/", "foo bar") -> []
func OnlyAlphanumeric ¶ added in v1.1.0
OnlyAlphanumeric removes all non-alphanumeric characters from a string. This includes spaces, punctuation, and special characters.
Parameters:
- s: The string to process
Returns:
- string: The string with only alphanumeric characters
Example:
OnlyAlphanumeric("Hello, World!") -> "HelloWorld" OnlyAlphanumeric("abc123") -> "abc123" OnlyAlphanumeric("a b c") -> "abc" OnlyAlphanumeric("!@#$%^") -> ""
func PadLeft ¶ added in v1.1.0
PadLeft pads a string on the left side with a specified character to reach the desired length. If the string is already longer than the specified length, it is returned unchanged.
Parameters:
- s: The string to pad
- padChar: The character to use for padding
- length: The desired total length
Returns:
- string: The padded string
Example:
PadLeft("123", '0', 5) -> "00123" PadLeft("abc", ' ', 6) -> " abc" PadLeft("hello", '*', 4) -> "hello" (no padding if string is already longer) PadLeft("", '-', 3) -> "---"
func PadRight ¶ added in v1.1.0
PadRight pads a string on the right side with a specified character to reach the desired length. If the string is already longer than the specified length, it is returned unchanged.
Parameters:
- s: The string to pad
- padChar: The character to use for padding
- length: The desired total length
Returns:
- string: The padded string
Example:
PadRight("123", '0', 5) -> "12300" PadRight("abc", ' ', 6) -> "abc " PadRight("hello", '*', 4) -> "hello" (no padding if string is already longer) PadRight("", '-', 3) -> "---"
func PascalCase ¶
PascalCase converts string to PascalCase format (also known as UpperCamelCase). It splits the string into words, capitalizes the first letter of each word, and joins them without separators.
Parameters:
- s: The string to convert to PascalCase
Returns:
- string: The PascalCase formatted string
Example:
PascalCase("hello world") -> "HelloWorld" PascalCase("hello-world") -> "HelloWorld" PascalCase("hello_world") -> "HelloWorld"
func Password ¶ added in v1.1.0
Password generates a random password with the given length. If no length is provided, the default length is 32 characters. The password will contain a mix of uppercase letters, lowercase letters, numbers, and special characters.
Parameters:
- length: The desired length of the password (optional, default: 32)
Returns:
- string: The generated random password
Example:
Password() -> "EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4" (random 32-character password) Password(12) -> "qwuar>#V|i]N" (random 12-character password)
func Plural ¶ added in v1.1.0
Plural converts a singular word to its plural form. This is a simple implementation and may not work for all cases.
Parameters:
- s: The singular word to pluralize
Returns:
- string: The plural form of the word
Example:
Plural("book") -> "books" Plural("child") -> "children" (irregular plural) Plural("city") -> "cities" (y -> ies) Plural("box") -> "boxes" (x -> xes) Plural("day") -> "days" (vowel + y -> ys) Plural("") -> "" (empty string)
func Random ¶ added in v1.1.0
Random generates a random string of specified length.
Parameters:
- length: The desired length of the random string
Returns:
- string: The generated random string
Example:
Random(10) -> "a1b2c3d4e5" (random alphanumeric string of length 10) Random(5) -> "x7y9z" (random alphanumeric string of length 5) Random(0) -> "" (empty string)
func Remove ¶ added in v1.1.0
Remove removes all occurrences of a given substring or pattern from a string.
Parameters:
- search: The substring or pattern to remove (can be a string, character, or regular expression)
- subject: The string to remove occurrences from
Returns:
- string: The resulting string after removals
Example:
Remove("e", "Peter Piper picked a peck of pickled peppers.") -> "Ptr Pipr pickd a pck of pickld ppprs." Remove("abc", "abcdef") -> "def" Remove("[aeiou]", "Hello World", true) -> "Hll Wrld" (using regex)
func Repeat ¶
Repeat repeats a string n times.
Parameters:
- s: The string to repeat
- n: The number of times to repeat the string
Returns:
- string: The repeated string
Example:
Repeat("abc", 2) -> "abcabc" Repeat("abc", 0) -> "" Repeat("", 5) -> ""
func Replace ¶
Replace replaces all occurrences of a given value in a string with another value.
Parameters:
- search: The string to find
- replace: The string to replace with
- subject: The string to perform replacements on
Returns:
- string: The resulting string after replacements
Example:
Replace("Fred", "Barney", "Hi Fred") -> "Hi Barney" Replace("d", "e", "abc") -> "abc" (no change if search string not found) Replace("a", "b", "") -> "" (no change for empty string)
func ReplaceArray ¶ added in v1.1.0
ReplaceArray replaces a search string with an array of replacements sequentially.
Parameters:
- search: The string to find
- replace: Array of replacement strings
- subject: The string to perform replacements on
Returns:
- string: The resulting string after replacements
Example:
ReplaceArray("?", []string{"a", "b", "c"}, "? and ? and ?") -> "a and b and c" ReplaceArray("?", []string{"a", "b"}, "? and ? and ?") -> "a and b and ?" (not enough replacements) ReplaceArray("?", []string{"a", "b", "c", "d"}, "? and ?") -> "a and b" (extra replacements ignored) ReplaceArray("not found", []string{"replacement"}, "hello world") -> "hello world" (search not found)
func ReplaceFirst ¶ added in v1.1.0
ReplaceFirst replaces the first occurrence of a given value in a string.
Parameters:
- search: The string to find
- replace: The string to replace with
- subject: The string to perform replacement on
Returns:
- string: The resulting string after replacement
Example:
ReplaceFirst("a", "x", "ababa") -> "xbaba" ReplaceFirst("hello", "hi", "hello world hello") -> "hi world hello" ReplaceFirst("not found", "replacement", "hello world") -> "hello world" (search not found)
func ReplaceLast ¶ added in v1.1.0
ReplaceLast replaces the last occurrence of a given value in a string.
Parameters:
- search: The string to find
- replace: The string to replace with
- subject: The string to perform replacement on
Returns:
- string: The resulting string after replacement
Example:
ReplaceLast("a", "x", "ababa") -> "ababx" ReplaceLast("hello", "hi", "hello world hello") -> "hello world hi" ReplaceLast("not found", "replacement", "hello world") -> "hello world" (search not found)
func ReplaceMatches ¶ added in v1.1.0
ReplaceMatches replaces all occurrences of a pattern in a string using a regular expression. The replacement can be either a string or a function that returns a string.
Parameters:
- pattern: The regular expression pattern to match
- replace: The replacement (string or function that takes a match array and returns a string)
- subject: The string to perform replacements on
Returns:
- string: The resulting string after replacements
Example:
ReplaceMatches("/[^A-Za-z0-9]++/", "", "(+1) 501-555-1000") -> "15015551000" ReplaceMatches("/\\d/", func(matches []string) string { return "[" + matches[0] + "]" }, "123") -> "[1][2][3]"
func Reverse ¶ added in v1.1.0
Reverse reverses the characters in a string. It properly handles UTF-8 encoded strings by working with runes.
Parameters:
- s: The string to reverse
Returns:
- string: The reversed string
Example:
Reverse("hello") -> "olleh" Reverse("Hello, 世界") -> "界世 ,olleH" Reverse("") -> "" Reverse("a") -> "a"
func Rtrim ¶ added in v1.1.0
Rtrim removes specified characters from the end of a string.
Parameters:
- s: The string to trim
- chars: The characters to remove
Returns:
- string: The right-trimmed string
Example:
Rtrim("hello ", " ") -> "hello" Rtrim("helloxxx", "x") -> "hello" Rtrim("hello world", "world ") -> "hello" Rtrim("hello", "x") -> "hello" (no characters to trim) Rtrim("", "x") -> "" (empty string)
func Singular ¶ added in v1.1.0
Singular converts a plural word to its singular form. This is a simple implementation and may not work for all cases.
Parameters:
- s: The plural word to singularize
Returns:
- string: The singular form of the word
Example:
Singular("books") -> "book" Singular("children") -> "child" (irregular plural) Singular("cities") -> "city" (ies -> y) Singular("boxes") -> "box" (es -> "") Singular("days") -> "day" (s -> "") Singular("") -> "" (empty string)
func Slugify ¶ added in v1.1.0
Slugify converts a string to a URL-friendly slug. It performs the following transformations:
- Converts to lowercase
- Replaces spaces with hyphens
- Removes all special characters except letters, numbers and hyphens
- Replaces multiple hyphens with a single hyphen
- Trims hyphens from start and end
Parameters:
- s: The input string to convert to slug
Returns:
- string: A URL-friendly slug string
Example:
Slugify("Hello World") -> "hello-world" Slugify("Hello, World!") -> "hello-world" Slugify(" Hello World ") -> "hello-world" Slugify("Hello--World") -> "hello-world"
func SnakeCase ¶
SnakeCase converts a string to snake_case format. It splits the string into words, converts them to lowercase, and joins them with underscores. Special characters are removed and multiple underscores are replaced with a single underscore.
Parameters:
- s: The string to convert to snake_case
Returns:
- string: The snake_case formatted string
Example:
SnakeCase("hello world") -> "hello_world" SnakeCase("HelloWorld") -> "hello_world" SnakeCase("HELLO-WORLD") -> "hello_world"
func Split ¶
Split splits a string by the given separator.
Parameters:
- s: The string to split
- separator: The separator to split by
Returns:
- []string: An array of substrings
Example:
Split("a-b-c", "-") -> ["a", "b", "c"] Split("a", "-") -> ["a"] Split("", "-") -> [""]
func Squish ¶ added in v1.1.0
Squish removes all extraneous white space from a string, including extraneous white space between words.
Parameters:
- s: The string to squish
Returns:
- string: The string with all extraneous white space removed
Example:
Squish(" laravel framework ") -> "laravel framework" Squish("hello world") -> "hello world" Squish(" ") -> "" Squish("") -> ""
func Start ¶ added in v1.1.0
Start prepends a value to a string if it doesn't already start with it.
Parameters:
- s: The string to prepend to
- prefix: The string to prepend
Returns:
- string: The resulting string
Example:
Start("world", "hello ") -> "hello world" Start("hello world", "hello ") -> "hello world" (already starts with prefix) Start("hello", "") -> "hello" (empty prefix) Start("", "hello") -> "hello" (empty string)
func StartsWith ¶
StartsWith checks if a string starts with any of the given substrings. It checks each substring and returns true as soon as it finds a match.
Parameters:
- s: The string to check
- substrings: One or more substrings to check for at the beginning of the string
Returns:
- bool: True if the string starts with any of the given substrings, false otherwise
Example:
StartsWith("abc", "a") -> true StartsWith("abc", "ab") -> true StartsWith("abc", "abc") -> true StartsWith("abc", "d") -> false StartsWith("abc", "a", "b", "c") -> true StartsWith("", "") -> true
func Studly ¶ added in v1.1.0
Studly converts a string to StudlyCase format.
Parameters:
- s: The string to convert
Returns:
- string: The StudlyCase formatted string
Example:
Studly("hello_world") -> "HelloWorld" Studly("hello-world") -> "HelloWorld" Studly("hello world") -> "HelloWorld" Studly("hello_WORLD") -> "HelloWorld"
func Substr ¶ added in v1.1.0
Substr returns a portion of a string based on start position and length.
Parameters:
- s: The string to get a substring from
- start: Starting position
- length: Length of substring
Returns:
- string: The substring
Example:
Substr("hello world", 0, 5) -> "hello" Substr("hello world", 6, 5) -> "world" Substr("hello world", -5, 5) -> "world" (negative start counts from end) Substr("hello world", 0, -6) -> "hello" (negative length counts from end) Substr("hello world", 20, 5) -> "" (start beyond string length)
func Swap ¶ added in v1.1.0
Swap replaces multiple values in a string with their corresponding replacements.
Parameters:
- replacements: A map of search strings to their replacements
- subject: The string to perform replacements on
Returns:
- string: The resulting string after all replacements
Example:
Swap(map[string]string{"Tacos": "Burritos", "great": "fantastic"}, "Tacos are great!") -> "Burritos are fantastic!" Swap(map[string]string{"a": "x", "b": "y"}, "abc") -> "xyc" Swap(map[string]string{}, "hello world") -> "hello world" (no replacements)
func ToLower ¶
ToLower converts a string to lowercase.
Parameters:
- s: The string to convert to lowercase
Returns:
- string: The lowercase string
Example:
ToLower("FRED") -> "fred" ToLower("Fred") -> "fred" ToLower("fred") -> "fred" ToLower("") -> ""
func ToString ¶
ToString converts any value to its string representation.
Parameters:
- value: The value to convert to a string
Returns:
- string: The string representation of the value
Example:
ToString(123) -> "123" ToString(true) -> "true" ToString([]int{1, 2, 3}) -> "[1 2 3]"
func ToTitleCase ¶ added in v1.1.0
ToTitleCase converts a string to title case format where the first letter of each word is capitalized and the rest of the letters in each word are lowercase.
Parameters:
- s: The string to convert to title case
Returns:
- string: The title cased string
Example:
ToTitleCase("hello world") -> "Hello World" ToTitleCase("HELLO WORLD") -> "Hello World" ToTitleCase("hello WORLD") -> "Hello World" ToTitleCase("") -> ""
func ToUpper ¶
ToUpper converts a string to uppercase.
Parameters:
- s: The string to convert to uppercase
Returns:
- string: The uppercase string
Example:
ToUpper("fred") -> "FRED" ToUpper("Fred") -> "FRED" ToUpper("FRED") -> "FRED" ToUpper("") -> ""
func Trim ¶
Trim removes leading and trailing whitespace or specified characters from a string.
Parameters:
- s: The string to trim
- cutset: Optional string containing the characters to trim. If not provided, whitespace is trimmed.
Returns:
- string: The trimmed string
Example:
Trim(" abc ") -> "abc" Trim("-_-abc-_-", "-_") -> "abc" Trim("abc") -> "abc" Trim("") -> ""
func TrimEnd ¶
TrimEnd removes trailing whitespace or specified characters from a string.
Parameters:
- s: The string to trim
- cutset: Optional string containing the characters to trim from the end. If not provided, whitespace is trimmed.
Returns:
- string: The string with trailing characters removed
Example:
TrimEnd(" abc ") -> " abc" TrimEnd("-_-abc-_-", "-_") -> "-_-abc" TrimEnd("abc") -> "abc"
func TrimStart ¶
TrimStart removes leading whitespace or specified characters from a string.
Parameters:
- s: The string to trim
- cutset: Optional string containing the characters to trim from the start. If not provided, whitespace is trimmed.
Returns:
- string: The string with leading characters removed
Example:
TrimStart(" abc ") -> "abc " TrimStart("-_-abc-_-", "-_") -> "abc-_-" TrimStart("abc") -> "abc"
func Truncate ¶ added in v1.1.0
Truncate truncates a string to the specified length and adds an ellipsis if truncated. It returns the original string if its length is less than or equal to maxLength, otherwise returns the truncated string with "..." appended.
Parameters:
- s: The input string to truncate
- maxLength: The maximum allowed length of the string
Returns:
- string: The truncated string with "..." appended if truncation occurred, otherwise original string
Example:
Truncate("Hello, World", 5) -> "Hello..." Truncate("Hello", 10) -> "Hello" Truncate("", 5) -> "" Truncate("Hello", 0) -> ""
func TruncateWords ¶ added in v1.1.0
TruncateWords truncates a string to the specified number of words and adds an ellipsis if the string was truncated.
Parameters:
- s: The string to truncate
- maxWords: Maximum number of words to keep
Returns:
- string: The truncated string with "..." appended if truncation occurred
Example:
TruncateWords("hello world foo bar", 2) -> "hello world..." TruncateWords("hello world", 3) -> "hello world" TruncateWords("hello", 1) -> "hello" TruncateWords("", 5) -> "" TruncateWords("hello world", 0) -> ""
func Ucfirst ¶ added in v1.1.0
Ucfirst capitalizes the first character of a string.
Parameters:
- s: The string to capitalize
Returns:
- string: The string with first character capitalized
Example:
Ucfirst("hello") -> "Hello" Ucfirst("hello world") -> "Hello world" Ucfirst("Hello") -> "Hello" (already capitalized) Ucfirst("") -> "" (empty string)
func WordAt ¶ added in v1.1.0
WordAt returns the word at the specified position in a string.
Parameters:
- s: The input string.
- position: The position to check for a word (0-indexed).
Returns:
- string: The word at the specified position, or an empty string if the position is out of bounds.
Example:
WordAt("This is my name.", 6) -> "is" WordAt("Hello world", 0) -> "Hello" WordAt("Hello world", 6) -> "world" WordAt("Hello world", 12) -> "" (position out of bounds) WordAt("", 0) -> "" (empty string)
func Words ¶
Words splits string into an array of its words. It handles various word boundaries including camelCase, snake_case, and kebab-case.
Parameters:
- str: The string to split into words
Returns:
- []string: An array of words extracted from the string
Example:
Words("hello world") -> ["hello", "world"] Words("camelCase") -> ["camel", "case"] Words("snake_case") -> ["snake", "case"] Words("kebab-case") -> ["kebab", "case"]
func WordsPattern ¶
WordsPattern splits string into words using a custom pattern. The pattern is used as a regular expression to split the string.
Parameters:
- s: The string to split into words
- pattern: The regular expression pattern to use for splitting
Returns:
- []string: An array of words extracted from the string
Example:
WordsPattern("hello-world_test", `[\-_]+`) -> ["hello", "world", "test"] WordsPattern("a,b;c", `[,;]`) -> ["a", "b", "c"]
func Wordwrap ¶ added in v1.1.0
Wordwrap wraps a string to a given number of characters.
Parameters:
- s: The string to wrap
- width: The number of characters at which to wrap
- breakChar: The string to insert at break points
Returns:
- string: The wrapped string
Example:
Wordwrap("A very long sentence that needs wrapping.", 10, "\n") -> "A very\nlong\nsentence\nthat needs\nwrapping." Wordwrap("Short text", 20, "\n") -> "Short text" (no wrapping needed) Wordwrap("word word word", 5, "<br>") -> "word<br>word<br>word" Wordwrap("", 10, "\n") -> "" (empty string)
Types ¶
type ExcerptOptions ¶ added in v1.1.0
ExcerptOptions Default options struct