str

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 18 Imported by: 16

README

Str Package

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.
  • 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
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..."

// Convert to snake_case
snake := str.ToSnake("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
md5 := str.MD5("Hello World")  // "b10a8db164e0754105b7a99be72e3fe5"

// 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"
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"

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 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 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 MD5

func MD5(text string) string

MD5 converts a string to MD5 hash

func Random

func Random(length int) string

Random generates random string of specified length

func RandomFromGamma

func RandomFromGamma(length int, gamma string) string

RandomFromGamma generates random string of specified length with the characters specified in the gamma string

func RemovePrefix

func RemovePrefix(str string, prefix string) string

func RemoveSuffix

func RemoveSuffix(str string, suffix string) string

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 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 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 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 "£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 "£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 "£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 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 Upper

func Upper(str string) string

Upper returns the string in upper case.

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

This section is empty.

Jump to

Keyboard shortcuts

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