str

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2025 License: AGPL-3.0 Imports: 17 Imported by: 0

README

String 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

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

Usage Examples

String Validation
import "github.com/dracory/base/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/base/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/base/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/base/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"

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 added in v0.8.0

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 added in v0.8.0

func AddSlashesCustom(str string, escapeChars string) string

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

func After added in v0.7.0

func After(str, needle string) string

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

func AfterLast added in v0.7.0

func AfterLast(str, needle string) string

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

func Append added in v0.7.0

func Append(values ...string) string

Append appends one or more strings.

func Base32ExtendedDecode added in v0.7.0

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

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

func Base32ExtendedEncode added in v0.7.0

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

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

func Base64Decode added in v0.7.0

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

Base64Decode decodes base64 text to binary data.

func Base64Encode added in v0.7.0

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

Base64Encode encodes binary data to base64 encoded text.

func BcryptHashCompare added in v0.7.0

func BcryptHashCompare(str string, hash string) bool

BcryptHashCompare compares the string to a bcrypt hash

func Before added in v0.7.0

func Before(str, needle string) string

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

func BeforeLast added in v0.7.0

func BeforeLast(str, needle string) string

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

func Between added in v0.7.0

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

Between returns the string between two needles

func CharAt added in v0.7.0

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 ContainsAnyChar added in v0.7.0

func ContainsAnyChar(str string, charset string) bool

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

func ContainsOnly added in v0.7.0

func ContainsOnly(str string, charset string) bool

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

func IntToBase32 added in v0.7.0

func IntToBase32(num int) string

func IntToBase36 added in v0.7.0

func IntToBase36(num int) string

func Is added in v0.7.0

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

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

func IsAscii added in v0.7.0

func IsAscii(str string) bool

IsAscii returns true if the string contains only ASCII characters.

func IsEmpty added in v0.7.0

func IsEmpty(str string) bool

IsEmpty returns true if the string is empty.

func IsMap added in v0.7.0

func IsMap(str string) bool

IsMap returns true if the string is a valid Map.

func IsMatch added in v0.7.0

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

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

func IsNotEmpty added in v0.7.0

func IsNotEmpty(str string) bool

IsNotEmpty returns true if the string is not empty.

func IsSlice added in v0.7.0

func IsSlice(str string) bool

IsSlice returns true if the string is a valid Slice.

func IsUlid added in v0.7.0

func IsUlid(str string) bool

IsUlid returns true if the string is a valid ULID.

func IsUuid added in v0.7.0

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 added in v0.7.0

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 added in v0.7.0

func Random(length int) string

Random generates random string of specified length

func RandomFromGamma added in v0.7.0

func RandomFromGamma(length int, gamma string) string

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

func RemovePrefix added in v0.7.0

func RemovePrefix(str string, prefix string) string

func RemoveSuffix added in v0.7.0

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 added in v0.7.0

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

RightPad

func Slugify added in v0.7.0

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 added in v0.7.0

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 added in v0.7.0

func ToBcryptHash(str string) (string, error)

ToBcryptHash converts the string to bcrypt hash

func ToBytes added in v0.7.0

func ToBytes(s string) []byte

StrToBytes converts string to bytes

func ToCamel added in v0.7.0

func ToCamel(in string) string

func ToSnake added in v0.7.0

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 added in v0.7.0

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

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

func UcFirst added in v0.7.0

func UcFirst(str string) string

UcFirst convert first letter into upper.

func UcSplit added in v0.8.0

func UcSplit(s string) []string

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

func Upper added in v0.8.0

func Upper(str string) string

Upper returns the string in upper case.

func WordCount added in v0.8.0

func WordCount(str string) int

WordCount returns the number of words in the string.

func Words added in v0.8.0

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