str

package module
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2025 License: MIT Imports: 22 Imported by: 16

README

Str Package

Tests Status Go Report Card PkgGoDev

The str package provides a comprehensive set of string manipulation utilities for the Dracory framework. It offers a wide range of functions for string operations, validation, transformation, and formatting.

Overview

This package includes utilities for:

  1. String Manipulation: Functions for modifying, extracting, and transforming strings
  2. String Validation: Functions for checking string properties and patterns
  3. String Formatting: Functions for formatting strings in various ways
  4. String Conversion: Functions for converting between different string formats and encodings
  5. String Generation: Functions for generating random strings and hashes
  6. Price Formatting: Functions for formatting prices with currency symbols

Key Features

  • Pattern Matching: Check if strings match patterns using glob syntax
  • String Extraction: Extract substrings based on various criteria
  • String Transformation: Convert strings to different formats (camelCase, snake_case, etc.)
  • String Validation: Check if strings are empty, UUIDs, ULIDs, etc.
  • String Encoding: Encode and decode strings using various encodings (Base32, Base64, etc.)
  • String Hashing: Generate hashes from strings (MD5, BCrypt, etc.)
  • String Formatting: Format strings with padding, truncation, etc.
  • Conditional Helpers: Run callbacks when predicates (empty, pattern match, UUID/ULID, etc.) succeed
  • String Generation: Generate random strings and identifiers
  • Price Formatting: Format prices with currency symbols (USD, GBP, EUR)

Usage Examples

String Validation
import "github.com/dracory/str"

// Check if a string is empty
isEmpty := str.IsEmpty("")  // true

// Check if a string is not empty
isNotEmpty := str.IsNotEmpty("Hello")  // true

// Check if a string is a UUID
isUUID := str.IsUUID("123e4567-e89b-12d3-a456-426614174000")  // true

// Check if a string is a ULID
isULID := str.IsULID("01H9Z8K2P3M4N5Q6R7S8T9U0V")  // true

// Check if a string matches a pattern
matches := str.Is("hello.txt", "*.txt")  // true

// Check if a string matches a regular expression pattern
matchesRegex := str.Test("hello123", `^hello\d+$`)  // true
String Manipulation
import "github.com/dracory/str"

// Extract substring between two strings
between := str.Between("Hello [World] Test", "[", "]")  // "World"

// Extract substring before a string
before := str.Before("Hello World", "World")  // "Hello "

// Extract substring after a string
after := str.After("Hello World", "Hello ")  // "World"

// Extract substring before the last occurrence of a string
beforeLast := str.BeforeLast("Hello World World", "World")  // "Hello "

// Extract substring after the last occurrence of a string
afterLast := str.AfterLast("Hello World World", "World")  // ""

// Extract substring from the left
leftFrom := str.LeftFrom("Hello World", 5)  // "Hello"

// Extract substring from the right
rightFrom := str.RightFrom("Hello World", 5)  // "World"

// Truncate a string
truncated := str.Truncate("Hello World", 8, "...")  // "Hello..."

// Limit a string by rune length with optional suffix
limited := str.Limit("Hello World", 5)  // "Hello..."

// Convert to snake_case
snake := str.ToSnake("HelloWorld")  // "hello_world"

// Convert to kebab-case
kebab := str.Kebab("HelloWorld")  // "hello-world"

// Convert to camelCase
camel := str.ToCamel("hello_world")  // "helloWorld"

// Convert first character to uppercase
ucFirst := str.UcFirst("hello")  // "Hello"

// Convert string to uppercase
upper := str.Upper("hello")  // "HELLO"

// Split string into words
words := str.Words("Hello World")  // ["Hello", "World"]

// Count words in a string
wordCount := str.WordCount("Hello World")  // 2

// Create a URL-friendly slug
slug := str.Slugify("Hello World!", '-')  // "hello-world"
String Encoding and Hashing
import "github.com/dracory/str"

// Encode string to Base64
base64 := str.Base64Encode("Hello World")  // "SGVsbG8gV29ybGQ="

// Decode Base64 string
decoded := str.Base64Decode("SGVsbG8gV29ybGQ=")  // "Hello World"

// Encode string to Base32 Extended
base32 := str.Base32ExtendedEncode("Hello World")  // "91IMOR3FCPBI41"

// Decode Base32 Extended string
decoded := str.Base32ExtendedDecode("91IMOR3FCPBI41")  // "Hello World"

// Generate MD5 hash (legacy helper — DO NOT use for security-sensitive hashing)
md5 := str.MD5("Hello World")  // "b10a8db164e0754105b7a99be72e3fe5"

// Generate SHA-256 hash (preferred general-purpose hashing helper)
sha256 := str.SHA256("Hello World")  // "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e"

// Generate BCrypt hash
bcrypt := str.ToBcryptHash("password")  // "$2a$10$..."

// Compare password with BCrypt hash
matches := str.BcryptHashCompare("password", bcrypt)  // true
String Generation
import "github.com/dracory/str"

// Generate a random string
random := str.Random(10)  // "a1b2c3d4e5"

// Generate a random string from a gamma distribution
randomGamma := str.RandomFromGamma(10, 2.0, 1.0)  // "a1b2c3d4e5"

// Convert integer to Base32
base32 := str.IntToBase32(12345)  // "3RP"

// Convert integer to Base36
base36 := str.IntToBase36(12345)  // "9IX"
Conditional Helpers
import "github.com/dracory/str"

result := str.When("admin", str.Is("admin", "admin"), func(s string) string {
    return s + "@example.com"
})
// result == "[email protected]"

result = str.WhenEmpty("", func(_ string) string { return "fallback" })
// result == "fallback"

result = str.WhenIsUUID("123e4567-e89b-12d3-a456-426614174000", func(s string) string {
    return "valid:" + s
})
// result == "valid:123e4567-e89b-12d3-a456-426614174000"
Buffer Utility
import "github.com/dracory/str"

buf := str.NewBuffer()
buf.Append("user-")
buf.Append(42)
buf.Append(true)

result := buf.String()  // "user-42true"
Price Formatting
import "github.com/dracory/str"

// Get currency symbol (Unicode by default)
symbol := str.CurrencySymbol("USD")  // "$"
symbol := str.CurrencySymbol("GBP")  // "£"
symbol := str.CurrencySymbol("EUR")  // "€"
symbol := str.CurrencySymbol("JPY")  // "¥"
symbol := str.CurrencySymbol("INR")  // "₹"

// Get currency symbol as HTML entity
symbol := str.CurrencySymbol("GBP", true)  // "£"
symbol := str.CurrencySymbol("EUR", true)  // "€"

// Supports 40+ currencies including:
// Major: USD, EUR, GBP, JPY, CNY, INR, KRW, RUB, TRY
// Dollar variants: AUD, CAD, HKD, SGD, NZD, MXN, BRL, ARS
// European: CHF, SEK, NOK, DKK, PLN, CZK, HUF, RON, BGN
// Middle East & Africa: SAR, AED, ILS, ZAR, EGP, NGN, KES
// Asian: THB, IDR, MYR, PHP, VND, PKR, BDT
// Crypto: BTC, ETH

// Convert float to formatted price string (Unicode by default)
price := str.ToPrice(19.99, "USD")  // "$19.99"
price := str.ToPrice(100.00, "GBP")  // "£100.00"
price := str.ToPrice(5000.50, "JPY")  // "¥5000.50"

// Convert float to formatted price string with HTML entity
price := str.ToPrice(19.99, "GBP", true)  // "£19.99"
price := str.ToPrice(45.50, "EUR", true)  // "€45.50"

// Convert string to formatted price string (with error handling)
price, err := str.ToPriceFromString("19.99", "USD")  // "$19.99", nil
price, err := str.ToPriceFromString("invalid", "USD")  // "", error

// Convert string to formatted price string with HTML entity
price, err := str.ToPriceFromString("19.99", "GBP", true)  // "£19.99", nil

// Convert string to formatted price string (with default fallback)
price := str.ToPriceFromStringOrDefault("19.99", "USD", "n/a")  // "$19.99"
price := str.ToPriceFromStringOrDefault("invalid", "USD", "n/a")  // "n/a"

// Convert string to formatted price string with HTML entity and default fallback
price := str.ToPriceFromStringOrDefault("19.99", "EUR", "n/a", true)  // "€19.99"

## Function Reference

The following lists every exported helper, grouped by their primary area. Functions that accept variadic arguments support optional parameters for fine-grained control.

### Validation & Matching

- `Is(str, patterns ...string)` — checks glob patterns (e.g., `*.txt`).
- `IsMatch(str, pattern string)` — tests strings against regular expressions.
- `Test(str, pattern string)` — convenience regex check that ignores empty patterns.
- `Contains(str, value string)` — verifies a substring exists.
- `ContainsAll(str string, values []string)` — ensures all values occur in the string.
- `ContainsAnyChar(str, chars string)` — reports whether any rune from `chars` is present.
- `ContainsOnly(str, chars string)` — verifies every rune is within `chars`.
- `StartsWith(str string, prefixes ...string)` — checks prefix matches.
- `EndsWith(str string, suffixes ...string)` — checks suffix matches.
- `Exactly(str, value string)` — requires an exact match (string function); `(*StringBuilder).Exactly` compares the builder value.
- `Match(str, pattern string)` — finds the first regex match and returns it.
- `MatchAll(str, pattern string)` — returns all regex matches.
- `IsEmpty(str string)` / `IsNotEmpty(str string)` — emptiness predicates.
- `IsAscii(str string)` — ensures the string is ASCII-only.
- `IsUuid(str string)` / `IsUlid(str string)` — identifier validation helpers.
- `IsMap(v any)` / `IsSlice(v any)` — type assertions for dynamic values.

### Extraction & Structure

- `After(str, search string)` / `AfterLast(str, search string)` — substrings after a delimiter.
- `Before(str, search string)` / `BeforeLast(str, search string)` — substrings before a delimiter.
- `Between(str, start, end string)` / `BetweenFirst(str, start, end string)` — segments between markers.
- `LeftFrom(str string, index int)` / `RightFrom(str string, index int)` — slice from rune offsets.
- `Substr(str string, offset, length int)` — rune-aware substring extraction.
- `CharAt(str string, index int)` — retrieves a rune by position.
- `Excerpt(str, needle string, opts ...ExcerptOption)` — captures text surrounding a needle.
- `Split(str, delimiter string, limit ...int)` — delimiter-based splitting with optional limit.
- `Explode(str string, delimiter string)` — synonym for `Split` without limits.
- `Headline(str string)` — title-cases the string with headline rules.
- `Basename(path string)` / `Dirname(path string)` — filesystem-inspired helpers.
- `Length(str string)` — rune count for the string.
- `WordCount(str string)` — number of words in the string.
- `Words(str string, limit int, end ...string)` — truncates text by word count.

### Transformation & Case

- `ToCamel(str string)` — converts to `camelCase`.
- `ToSnake(str string)` — converts to snake_case using Go rules.
- `Snake(str string, delimiter ...string)` — snake_case with custom delimiter (used by `Kebab`).
- `Kebab(str string)` — outputs kebab-case (`hello-world`).
- `Studly(str string)` — creates StudlyCaps/PascalCase text.
- `Slugify(str string, delimiter rune)` — URL-friendly slugs with Unicode folding.
- `Title(str string)` — title-cases every word.
- `Upper(str string)` / `Lower(str string)` — upper/lower case transforms.
- `UcFirst(str string)` / `LcFirst(str string)` — adjust only the first rune.
- `Start(str, prefix string)` — idempotently prefixes a string.
- `Finish(str, suffix string)` — idempotently suffixes a string.
- `Swap(str string, search string, replace string)` — swaps substrings regardless of order.
- `Mask(str string, mask string, start, length int)` — masks ranges with a repeated mask string.
- `Limit(str string, length int, suffix ...string)` — rune-aware limiter with optional suffix.
- `Truncate(str string, length int, ellipsis string)` — truncates by rune length.
- `NewLine(str string, count ...int)` — appends newline characters (default `\n`).

### Whitespace & Padding

- `Trim(str string, characters ...string)` — trims characters or Unicode whitespace.
- `LTrim(str string, characters ...string)` / `RTrim(str string, characters ...string)` — leading/trailing trims.
- `PadLeft(str, pad string, length int)` / `PadRight(str, pad string, length int)` / `PadBoth(str, pad string, length int)` — symmetrical padding utilities.
- `LeftPad(str string, padStr string, overallLen int)` / `RightPad(str string, padStr string, overallLen int)` — legacy-style padding helpers.
- `Squish(str string)` — collapses consecutive whitespace into single spaces and trims edges.
- `ChopStart(str, prefix string)` / `ChopEnd(str, suffix string)` — remove prefixes/suffixes when present.

### Combination, Replacement & Formatting

- `Append(values ...string)` — concatenates strings efficiently (see also `(*buffer).Append`).
- `Prepend(str string, prefix string)` — adds a prefix once.
- `Repeat(str string, count int)` — repeats the string.
- `Remove(str string, values ...string)` — removes all occurrences of values.
- `RemovePrefix(str string, prefix string)` / `RemoveSuffix(str string, suffix string)` — trim single affixes.
- `Replace(str, search, replace string)` / `ReplaceFirst` / `ReplaceLast` — targeted replacements.
- `ReplaceMatches(str, pattern, replace string)` — regex replacement for each match.
- `ReplaceStart(str, search, replace string)` — prefix-specific replacement.
- `AddSlashes(str string)` — escapes quotes and backslashes.
- `AddSlashesCustom(str string, escapeChars string)` — escapes custom characters.
- `Explode(str string, delimiter string)` — splits into slices (alias of `Split`).

### Encoding, Conversion & Hashing

- `Base64Encode(str string)` / `Base64Decode(str string)` — Base64 conversions.
- `Base32ExtendedEncode(str string)` / `Base32ExtendedDecode(str string)` — Crockford-style Base32 helpers.
- `ToBytes(str string)` — converts to `[]byte` without extra allocation.
- `IntToBase32(n int)` / `IntToBase36(n int)` — integer radix conversions.
- `MD5(str string)` — hex-encoded MD5 hash.
  - ⚠️ Legacy helper; MD5 is insecure and must not be used for security-sensitive hashing.
- `SHA256(str string)` — hex-encoded SHA-256 hash for general-purpose hashing.
- `ToBcryptHash(password string)` — produces a BCrypt hash.
- `BcryptHashCompare(password, hash string)` — verifies BCrypt hashes.

### Generation & Randomness

- `Random(length int)` — cryptographically secure random string of the requested length.
- `RandomFromGamma(length int, shape, scale float64)` — gamma-distributed random strings.

### Price & Numeric Formatting

- `CurrencySymbol(code string, htmlEntity ...bool)` — ISO currency symbol lookup with optional HTML entities.
- `ToPrice(amount float64, code string, htmlEntity ...bool)` — formats prices with symbols.
- `ToPriceFromString(input, code string, htmlEntity ...bool)` — parses string input to a formatted price.
- `ToPriceFromStringOrDefault(input, code, fallback string, htmlEntity ...bool)` — safe parsing with fallback output.
- `Maximum(a, b int)` — max helper commonly used in formatting calculations.

### Flow Control & Conditional Helpers

- `When(str string, condition bool, truthy func(string) string, fallback ...func(string) string)` — conditional string transformer.
- `WhenEmpty`, `WhenNotEmpty`, `WhenContains`, `WhenContainsAll`, `WhenStartsWith`, `WhenEndsWith`, `WhenExactly`, `WhenNotExactly` — call `When` with pre-built predicates.
- `WhenIs`, `WhenIsAscii`, `WhenIsUuid`, `WhenIsUlid` — conditional helpers for pattern/content checks.
- `Unless(str string, predicate func(string) bool, fallback func(string) string)` — inverse of `When` using boolean predicate.
- `Pipe(str string, callback func(string) string)` — transforms via callback returning the new string.
- `Tap(str string, callback func(string))` — observes a string then returns it unchanged.

### Buffer Utility

- `NewBuffer()` — constructs a fluent `*buffer` wrapper around `bytes.Buffer`.
- `(*buffer).Append(v any)` — appends strings, numbers, booleans, runes, or bytes; returns the same buffer for chaining.

### String Builder

- `StringBuilder` — exported struct that accumulates string operations.
- `Of(value string)` — creates a new builder with the given value.
- `(*StringBuilder).Append(parts ...string)` — concatenates pieces.
- `(*StringBuilder).Prepend(prefix string)` — adds a prefix once.
- `(*StringBuilder).LTrim(chars ...string)` / `RTrim(chars ...string)` — trims builder contents in place.
- `(*StringBuilder).Exactly(str string)` — compares against a target value.
- `(*StringBuilder).Unless(predicate func(*StringBuilder) bool, fallback func(*StringBuilder) *StringBuilder)` — conditional mutation.
- `(*StringBuilder).String()` — returns the accumulated string.

### Miscellaneous Utilities

- `Slugify`, `Studly`, `Snake`, `Kebab`, `ToCamel`, `ToSnake`, `Title`, `Upper`, `Lower` — see Transformation section for common naming conversions.
- `Mask`, `Limit`, `Truncate`, `NewLine` — general-purpose helpers noted above but commonly reused across categories.
- `Append`, `Prepend`, `Remove`, `Replace*`, `AddSlashes*` — composition utilities summarized above.

## Best Practices

1. **Use Appropriate Functions**: Choose the most specific function for your task
2. **Handle Errors**: Check for errors when using functions that can fail
3. **Consider Performance**: Some functions may be more efficient than others for your use case
4. **Validate Input**: Always validate input strings before processing them
5. **Use Constants**: Use constants for repeated string values

## License

This package is part of the dracory/base project and is licensed under the same terms. 

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSlashes

func AddSlashes(str string) string

AddSlashes returns a string with backslashes added before characters that need to be escaped.

These characters are: single quote (') double quote (") backslash (\)

func AddSlashesCustom

func AddSlashesCustom(str string, escapeChars string) string

AddSlashesCustom returns a string with backslashes added before characters specified in the escapeChars string.

func After

func After(str, needle string) string

After returns the substring after the first occurrence of the specified needle.

func AfterLast

func AfterLast(str, needle string) string

AfterLast returns the substring after the last occurrence of the specified needle.

func Append

func Append(values ...string) string

Append appends one or more strings.

func Base32ExtendedDecode

func Base32ExtendedDecode(data []byte) (text []byte, err error)

Base32ExtendedDecode encodes binary data to base32 extended (RFC 4648) encoded text.

func Base32ExtendedEncode

func Base32ExtendedEncode(data []byte) (text []byte, err error)

Base32ExtendedEncode encodes binary data to base32 extended (RFC 4648) encoded text.

func Base64Decode

func Base64Decode(text []byte) (data []byte, err error)

Base64Decode decodes base64 text to binary data.

func Base64Encode

func Base64Encode(data []byte) (text []byte, err error)

Base64Encode encodes binary data to base64 encoded text.

func Basename added in v0.6.0

func Basename(p string, suffix ...string) string

Basename returns the basename of the file path string, and trims the suffix based on the parameter (optional). Example: Basename("/path/to/file.txt") returns "file.txt" Example: Basename("/path/to/file.txt", ".txt") returns "file"

func BcryptHashCompare

func BcryptHashCompare(str string, hash string) bool

BcryptHashCompare compares the string to a bcrypt hash

func Before

func Before(str, needle string) string

Before returns the substring before the first occurrence of the specified search string.

func BeforeLast

func BeforeLast(str, needle string) string

BeforeLast returns the substring before the last occurrence of the specified search string.

func Between

func Between(str string, startNeedle string, endNeedle string) (result string, found bool)

Between returns the string between two needles

func BetweenFirst added in v0.6.0

func BetweenFirst(str, start, end string) string

BetweenFirst returns the substring between the first occurrence of the start string and the first occurrence of the end string after the start. If either start or end is empty or not found, returns empty string. Example: BetweenFirst("Hello [World] and [Universe]", "[", "]") returns "World"

func CharAt

func CharAt(str string, index int) string

CharAt returns the character at the specified index.

If the specified index is negative, it is counted from the end of the string.

Business logic: 1. Convert the string to a rune slice for proper handling of UTF-8 encoding. 2. Get the length of the rune slice. 3. Handle negative indices by converting them to positive indices (e.g. -1 -> length - 1). 4. Check if the index is out of bounds. 5. If the index is out of bounds, return an empty string. 6. Return the character at the specified index.

Example:

str.CharAt("Hello World", 0) // Returns "H"
str.CharAt("Hello World", -1) // Returns "d"
str.CharAt("Hello World", 20) // Returns ""

Parameters: - str: The string to get the character from. - index: The index of the character to get.

Returns: - The character at the specified index.

func ChopEnd added in v0.6.0

func ChopEnd(str string, needle string, more ...string) string

ChopEnd removes the first matching suffix found in needle or more from the end of str. If none of the provided suffixes match, the original string is returned unchanged.

func ChopStart added in v0.6.0

func ChopStart(str string, needle string, more ...string) string

ChopStart removes the first matching prefix found in needle or more from the start of str. If none of the provided prefixes match, the original string is returned unchanged.

func Contains added in v0.6.0

func Contains(str string, values ...string) bool

Contains returns true if str contains any of the provided values. Empty values are ignored. If no non-empty values are provided, returns false.

func ContainsAll added in v0.6.0

func ContainsAll(str string, values ...string) bool

ContainsAll returns true if str contains all the provided values. Empty values are treated as matches (consistent with strings.Contains behaviour).

func ContainsAnyChar

func ContainsAnyChar(str string, charset string) bool

ContainsAnyChar returns true if the string contains any of the characters in the provided charset

func ContainsOnly

func ContainsOnly(str string, charset string) bool

ContainsOnly returns true is the string contains only charcters from the specified charset

func CurrencySymbol added in v0.5.0

func CurrencySymbol(currencyCode string, htmlEntity ...bool) string

CurrencySymbol returns the symbol for the given ISO 4217 currency code. By default, returns the Unicode symbol. Pass true to get HTML entity instead. Returns the original currency code if not recognized. Example: CurrencySymbol("USD") returns "$" Example: CurrencySymbol("GBP", true) returns "£"

func Dirname added in v0.7.0

func Dirname(p string, levels ...int) string

Dirname returns the directory portion of the provided path. By default it returns the parent directory; provide levels to traverse multiple parents.

func EndsWith added in v0.7.0

func EndsWith(str string, values ...string) bool

EndsWith returns true if str ends with any of the provided values. Empty values are ignored. If no non-empty values are provided, returns false.

func Exactly added in v0.7.0

func Exactly(str, value string) bool

Exactly returns true if str is exactly equal to value.

func Excerpt added in v0.7.0

func Excerpt(str, phrase string, options ...ExcerptOption) string

Excerpt returns a substring surrounding the first occurrence of phrase. The radius controls how many runes are kept on each side of the phrase, and omission specifies the string to append when content is truncated. If phrase is not found, the original string is returned unchanged.

func Explode added in v0.7.0

func Explode(str, delimiter string, limit ...int) []string

Explode splits the input string using the provided delimiter. An optional limit mirrors PHP's explode semantics:

>0 keeps at most limit elements, combining the remainder into the last element.
<0 omits the last |limit| elements.
0 is treated as if no limit was provided.

func Finish added in v0.7.0

func Finish(str, suffix string) string

Finish appends the suffix to str, ensuring it appears only once at the end.

func Headline added in v0.7.0

func Headline(in string) string

Headline converts a string into headline case. When the input already contains whitespace, it is simply title-cased. Otherwise, the string is normalized, converted to studly case, split on uppercase boundaries, and the resulting words are joined with spaces.

func IntToBase32

func IntToBase32(num int) string

func IntToBase36

func IntToBase36(num int) string

func Is

func Is(str string, patterns ...string) bool

Is returns true if the string matches any of the given patterns.

func IsAscii

func IsAscii(str string) bool

IsAscii returns true if the string contains only ASCII characters.

func IsEmpty

func IsEmpty(str string) bool

IsEmpty returns true if the string is empty.

func IsMap

func IsMap(str string) bool

IsMap returns true if the string is a valid Map.

func IsMatch

func IsMatch(str string, patterns ...string) bool

IsMatch returns true if the string matches any of the given patterns.

func IsNotEmpty

func IsNotEmpty(str string) bool

IsNotEmpty returns true if the string is not empty.

func IsSlice

func IsSlice(str string) bool

IsSlice returns true if the string is a valid Slice.

func IsUlid

func IsUlid(str string) bool

IsUlid returns true if the string is a valid ULID.

func IsUuid

func IsUuid(str string) bool

IsUuid returns true if the string is a valid UUID.

func Kebab added in v0.16.0

func Kebab(str string) string

Kebab converts the input string to kebab-case.

func LTrim added in v0.8.0

func LTrim(in string, characters ...string) string

LTrim removes leading characters from the input string. When no character set is provided, leading Unicode whitespace is trimmed.

func LcFirst added in v0.7.0

func LcFirst(in string) string

LcFirst lowercases the first rune of the string.

func LeftFrom

func LeftFrom(str, needle string) string

LeftFrom returns the substring on the left side of the needle

func LeftPad

func LeftPad(s string, padStr string, overallLen int) string

LeftPad

func Length added in v0.7.0

func Length(in string) int

Length returns the number of runes in the given string.

func Limit added in v0.16.0

func Limit(str string, limit int, end ...string) string

Limit truncates the string to the given length, appending the provided ending (or "..." by default) when truncation occurs. Length is measured in runes.

func Lower added in v0.7.0

func Lower(in string) string

Lower converts the entire string to lower case.

func MD5

func MD5(text string) string

MD5 converts a string to an MD5 hash.

WARNING: MD5 is cryptographically broken and must not be used for security- sensitive purposes such as password hashing or integrity checks. This helper is retained for backward compatibility only; prefer SHA-256 via SHA256 (or stronger) for general hashing needs and BCrypt for passwords.

func Mask added in v0.8.0

func Mask(in, character string, index int, length ...int) string

Mask replaces a portion of the string with a repeated masking character. The index marks the starting rune offset, with negative values counting backwards from the end. If length is omitted the remainder of the string is masked. When the masking character is empty or the target segment is empty, the original string is returned unchanged.

func Match added in v0.8.0

func Match(in, pattern string) string

Match returns the first substring that matches the provided regular expression. If the pattern is empty, the original string is returned unchanged.

func MatchAll added in v0.8.0

func MatchAll(in, pattern string) []string

MatchAll returns all substrings that match the provided regular expression. If the pattern is empty, the entire string is returned as the single result.

func Maximum added in v0.7.0

func Maximum(a, b int) int

Maximum returns the larger of two integers.

func NewBuffer added in v0.16.0

func NewBuffer() *buffer

NewBuffer creates a new buffer instance.

func NewLine added in v0.8.0

func NewLine(in string, count ...int) string

NewLine appends new line characters to the input string. When no count is provided, a single newline is appended. Otherwise, count[0] specifies how many newline characters to add.

func PadBoth added in v0.8.0

func PadBoth(str string, length int, pad ...string) string

PadBoth pads the string on both sides to reach the desired length. Padding is evenly split between the left and right; when an odd number of characters is required, the extra character is added to the right side. The optional pad argument specifies the padding characters; it defaults to a single space when omitted or empty.

func PadLeft added in v0.8.0

func PadLeft(str string, length int, pad ...string) string

PadLeft pads the string on the left to reach the specified length. When the pad argument is omitted or empty, spaces are used.

func PadRight added in v0.8.0

func PadRight(str string, length int, pad ...string) string

PadRight pads the string on the right to reach the specified length. When the pad argument is omitted or empty, spaces are used.

func Pipe added in v0.8.0

func Pipe(in string, callback func(string) string) string

Pipe passes the string through the provided callback and returns the result. If callback is nil, the original string is returned unchanged.

func Prepend added in v0.9.0

func Prepend(str string, values ...string) string

Prepend concatenates the provided values before the input string.

func RTrim added in v0.13.0

func RTrim(str string, characters ...string) string

RTrim removes trailing characters from the input string. When no characters are provided, Unicode whitespace is trimmed.

func Random

func Random(length int) string

Random generates an alphanumeric string of the specified length using crypto/rand with rejection sampling to keep the character distribution unbiased.

Business Logic:

  1. Directly using raw crypto/rand bytes (e.g. by base64-encoding and truncating) skews character frequency, so we discard out-of-range samples before mapping.
  2. Alphanumeric output (letters and digits only) keeps the resulting tokens URL, filename, and copy/paste friendly.

func RandomFromGamma

func RandomFromGamma(length int, gamma string) (string, error)

RandomFromGamma generates a random string of specified length using the characters provided in gamma. It returns an error when length is not positive, gamma is empty, or when secure randomness cannot be generated.

func Remove added in v0.10.0

func Remove(str string, values ...string) string

Remove deletes all occurrences of the provided values from the input string.

func RemovePrefix

func RemovePrefix(str string, prefix string) string

func RemoveSuffix

func RemoveSuffix(str string, suffix string) string

func Repeat added in v0.10.0

func Repeat(in string, times int) string

Repeat repeats the input string the specified number of times.

func Replace added in v0.11.0

func Replace(str, search, replace string, caseSensitive ...bool) string

Replace substitutes occurrences of search with replace. Case sensitivity can be controlled via the optional caseSensitive flag (defaults to true).

func ReplaceFirst added in v0.11.0

func ReplaceFirst(str, search, replace string) string

ReplaceFirst replaces the first occurrence of search with replace. If search is empty, the original string is returned unchanged.

func ReplaceLast added in v0.12.0

func ReplaceLast(str, search, replace string) string

ReplaceLast replaces the last occurrence of search with replace. If search is empty or not found, the original string is returned unchanged.

func ReplaceMatches added in v0.12.0

func ReplaceMatches(str, pattern, replace string) string

ReplaceMatches replaces all substrings matching the pattern with the provided replacement string. If the pattern is empty, the original string is returned unchanged.

func ReplaceStart added in v0.12.0

func ReplaceStart(str, search, replace string) string

ReplaceStart replaces the beginning of the string if it starts with search. If search is empty or not present at the start, the original string is returned.

func RightFrom

func RightFrom(str, needle string) string

RightFrom returns the substring on the left side of the needle

func RightPad

func RightPad(s string, padStr string, overallLen int) string

RightPad

func SHA256 added in v0.17.0

func SHA256(text string) string

SHA256 returns the SHA-256 hash of the provided text encoded as a hex string.

func Slugify

func Slugify(s string, replaceWith rune) string

StrSlugify replaces each run of characters which are not ASCII letters or numbers with the Replacement character, except for leading or trailing runs. Letters will be stripped of diacritical marks and lowercased. Letter or number codepoints that do not have combining marks or a lower-cased variant will be passed through unaltered.

func Snake added in v0.13.0

func Snake(str string, delimiter ...string) string

Snake converts the string to snake case using the provided delimiter. The delimiter defaults to underscore when not specified or empty.

func Split added in v0.13.0

func Split(str, pattern string, limit ...int) []string

Split divides the string using the provided regex pattern. The optional limit matches regexp.Split behaviour: default -1 keeps all substrings.

func Squish added in v0.13.0

func Squish(str string) string

Squish collapses consecutive whitespace into a single space and trims leading/trailing whitespace.

func Start added in v0.14.0

func Start(str, prefix string) string

Start ensures the string begins with the provided prefix without duplicating it. If the prefix is empty, the original string is returned.

func StartsWith added in v0.14.0

func StartsWith(str string, values ...string) bool

StartsWith returns true if the string starts with any of the provided values. When no values are supplied, it returns false.

func Studly added in v0.7.0

func Studly(in string) string

Studly converts a string to StudlyCase (also known as UpperCamelCase).

func Substr

func Substr(str string, start int, length ...int) string

Substr returns a substring of a given string, starting at the specified index and with a specified length. It handles UTF-8 encoded strings.

func Swap added in v0.14.0

func Swap(str string, replacements map[string]string) string

Swap replaces occurrences of keys in the replacements map with their values. If the map is empty or contains an empty key, the original string is returned.

func Tap added in v0.14.0

func Tap(str string, callback func(string)) string

Tap passes the string to the provided callback and returns the original string unchanged. A nil callback is safely ignored.

func Test added in v0.16.0

func Test(str, pattern string) bool

Test returns true if the string matches the given regular expression pattern. Empty patterns always return false.

func Title added in v0.7.0

func Title(in string) string

Title returns the input string converted to title case using the default language-independent rules.

func ToBcryptHash

func ToBcryptHash(str string) (string, error)

ToBcryptHash converts the string to bcrypt hash

func ToBytes

func ToBytes(s string) []byte

StrToBytes converts string to bytes

func ToCamel

func ToCamel(in string) string

func ToPrice added in v0.5.0

func ToPrice(price float64, currencyCode string, htmlEntity ...bool) string

ToPrice converts a float64 price to a formatted string with the given ISO 4217 currency code. The price is formatted to 2 decimal places. By default, returns Unicode symbol. Pass true to get HTML entity instead. Example: ToPrice(19.99, "USD") returns "$19.99" Example: ToPrice(19.99, "GBP", true) returns "&pound;19.99"

func ToPriceFromString added in v0.5.0

func ToPriceFromString(priceStr string, currencyCode string, htmlEntity ...bool) (string, error)

ToPriceFromString converts a string price to a formatted price string with the given ISO 4217 currency code. Returns an error if the string cannot be parsed as a float. The price is formatted to 2 decimal places. By default, returns Unicode symbol. Pass true to get HTML entity instead. Example: ToPriceFromString("19.99", "USD") returns "$19.99", nil Example: ToPriceFromString("19.99", "GBP", true) returns "&pound;19.99", nil

func ToPriceFromStringOrDefault added in v0.5.0

func ToPriceFromStringOrDefault(priceStr string, currencyCode string, defaultValue string, htmlEntity ...bool) string

ToPriceFromStringOrDefault converts a string price to a formatted price string with the given ISO 4217 currency code. Returns the defaultValue if the string cannot be parsed as a float. The price is formatted to 2 decimal places. By default, returns Unicode symbol. Pass true to get HTML entity instead. Example: ToPriceFromStringOrDefault("19.99", "USD", "n/a") returns "$19.99" Example: ToPriceFromStringOrDefault("invalid", "USD", "n/a") returns "n/a" Example: ToPriceFromStringOrDefault("19.99", "GBP", "n/a", true) returns "&pound;19.99"

func ToSnake

func ToSnake(in string) string

ToSnake convert the given string to snake case following the Golang format: acronyms are converted to lower-case and preceded by an underscore.

func Trim added in v0.15.0

func Trim(str string, characters ...string) string

Trim removes the provided characters from both ends of the string. When no characters are provided, Unicode spaces are removed.

func Truncate

func Truncate(str string, length int, ellipsis string) string

Truncate truncates a string to a given length, adding an ellipsis if necessary.

func UcFirst

func UcFirst(str string) string

UcFirst convert first letter into upper.

func UcSplit

func UcSplit(s string) []string

UcSplit splits the string into words using uppercase characters as the delimiter.

func Unless added in v0.15.0

func Unless(str string, predicate func(string) bool, fallback func(string) string) string

Unless executes the fallback when the predicate returns false, otherwise it returns the original string unchanged.

func Upper

func Upper(str string) string

Upper returns the string in upper case.

func When added in v0.16.0

func When(str string, condition bool, truthy func(string) string, fallback ...func(string) string) string

When executes the truthy callback when condition is true, otherwise executes the fallback if provided. It returns the resulting string.

func WhenContains added in v0.16.0

func WhenContains(str, value string, truthy func(string) string, fallback ...func(string) string) string

WhenContains executes the truthy callback when the string contains value. Otherwise it executes the fallback if provided.

func WhenContainsAll added in v0.16.0

func WhenContainsAll(str string, values []string, truthy func(string) string, fallback ...func(string) string) string

WhenContainsAll executes the truthy callback when the string contains all provided values. Otherwise it executes the fallback if present.

func WhenEmpty added in v0.16.0

func WhenEmpty(str string, truthy func(string) string, fallback ...func(string) string) string

WhenEmpty executes the truthy callback when the string is empty; otherwise it executes the fallback if supplied.

func WhenEndsWith added in v0.16.0

func WhenEndsWith(str string, values []string, truthy func(string) string, fallback ...func(string) string) string

WhenEndsWith executes the truthy callback when the string ends with any of the provided values; otherwise it executes the fallback if present.

func WhenExactly added in v0.16.0

func WhenExactly(str, value string, truthy func(string) string, fallback ...func(string) string) string

WhenExactly executes the truthy callback when the string exactly matches the provided value; otherwise it executes the fallback if present.

func WhenIs added in v0.16.0

func WhenIs(str string, patterns []string, truthy func(string) string, fallback ...func(string) string) string

WhenIs executes the truthy callback when the string matches any of the provided glob patterns; otherwise it executes the fallback if present.

func WhenIsAscii added in v0.16.0

func WhenIsAscii(str string, truthy func(string) string, fallback ...func(string) string) string

WhenIsAscii executes the truthy callback when the string is ASCII-only; otherwise it executes the fallback if supplied.

func WhenIsUlid added in v0.16.0

func WhenIsUlid(str string, truthy func(string) string, fallback ...func(string) string) string

WhenIsUlid executes the truthy callback when the string is a valid ULID; otherwise it executes the fallback if present.

func WhenIsUuid added in v0.16.0

func WhenIsUuid(str string, truthy func(string) string, fallback ...func(string) string) string

WhenIsUuid executes the truthy callback when the string is a valid UUID; otherwise it executes the fallback if present.

func WhenNotEmpty added in v0.16.0

func WhenNotEmpty(str string, truthy func(string) string, fallback ...func(string) string) string

WhenNotEmpty executes the truthy callback when the string is not empty; otherwise it executes the fallback if provided.

func WhenNotExactly added in v0.16.0

func WhenNotExactly(str, value string, truthy func(string) string, fallback ...func(string) string) string

WhenNotExactly executes the truthy callback when the string does not exactly match the provided value; otherwise it executes the fallback if present.

func WhenStartsWith added in v0.16.0

func WhenStartsWith(str string, values []string, truthy func(string) string, fallback ...func(string) string) string

WhenStartsWith executes the truthy callback when the string starts with any of the provided values; otherwise it executes the fallback if present.

func WordCount

func WordCount(str string) int

WordCount returns the number of words in the string.

func Words

func Words(str string, limit int, end ...string) string

Words returns the string truncated to the given number of words. If limit is less than 1, it returns an empty string. If limit is greater than or equal to the number of words, it returns the full string. An optional end string can be provided to customize the truncation suffix.

Types

type ExcerptOption added in v0.7.0

type ExcerptOption struct {
	Radius   int
	Omission string
}

ExcerptOption configures the behaviour of Excerpt.

type StringBuilder added in v0.7.0

type StringBuilder struct {
	// contains filtered or unexported fields
}

func Of added in v0.7.0

func Of(value string) *StringBuilder

func (*StringBuilder) Append added in v0.7.0

func (sb *StringBuilder) Append(parts ...string) *StringBuilder

func (*StringBuilder) Exactly added in v0.7.0

func (sb *StringBuilder) Exactly(str string) bool

func (*StringBuilder) LTrim added in v0.7.0

func (sb *StringBuilder) LTrim(chars ...string) *StringBuilder

func (*StringBuilder) Prepend added in v0.7.0

func (sb *StringBuilder) Prepend(prefix string) *StringBuilder

func (*StringBuilder) RTrim added in v0.7.0

func (sb *StringBuilder) RTrim(chars ...string) *StringBuilder

func (*StringBuilder) String added in v0.7.0

func (sb *StringBuilder) String() string

func (*StringBuilder) Unless added in v0.7.0

func (sb *StringBuilder) Unless(predicate func(*StringBuilder) bool, fallback func(*StringBuilder) *StringBuilder) *StringBuilder

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL