tinystring

package module
v0.0.15 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2025 License: MIT Imports: 3 Imported by: 7

README

TinyString

TinyString is a lightweight Go library that provides text manipulation with a fluid API, without external dependencies or standard library dependencies.

Features

  • 🚀 Fluid and chainable API
  • 🔄 Common text transformations
  • 🧵 Concurrency safe
  • 📦 No external dependencies
  • 🎯 Easily extensible
  • 🔄 Support for converting any data type to string

Installation

go get github.com/cdvelop/tinystring

Usage

import "github.com/cdvelop/tinystring"

// Basic example with string
text := tinystring.Convert("MÍ téxtO").RemoveTilde().String()
// Result: "MI textO"

// Examples with other data types
numText := tinystring.Convert(42).String()
// Result: "42"

boolText := tinystring.Convert(true).ToUpper().String()
// Result: "TRUE"

floatText := tinystring.Convert(3.14).String()
// Result: "3.14"

// Chaining operations
text := tinystring.Convert("Él Múrcielago Rápido")
    .RemoveTilde()
    .CamelCaseLower()
    .String()
// Result: "elMurcielagoRapido"
Available Operations
  • Convert(v any): Initialize text processing with any data type (string, int, float, bool, etc.)
  • RemoveTilde(): Removes accents and diacritics (e.g. "café" -> "cafe")
  • ToLower(): Converts to lowercase (e.g. "HELLO" -> "hello")
  • ToUpper(): Converts to uppercase (e.g. "hello" -> "HELLO")
  • Capitalize(): Capitalizes the first letter of each word (e.g. "hello world" -> "Hello World")
  • CamelCaseLower(): Converts to camelCase (e.g. "hello world" -> "helloWorld")
  • CamelCaseUpper(): Convert to UpperCase (e.g. "hello world" -> "HelloWorld")
  • ToSnakeCaseLower(): Converts to snake_case (e.g. "hello world" -> "hello_world"), With Other Params: ToSnakeCaseLower("-") -> "hello-world"
  • ToSnakeCaseUpper(): Convert to SNAKE_CASE (e.g. "hello world" -> "HELLO_WORLD"), With Other Params: ToSnakeCaseUpper("-") -> "HELLO-WORLD"
  • Split(data, separator string): Divides a string by a separator and returns a slice of substrings
  • ParseKeyValue(input string, delimiter string): Extracts the value from a key:value string format (e.g. ParseKeyValue("name:John") -> "John", nil)
  • Replace(old, new string): Replaces all occurrences of a substring (e.g. "hello world" -> "hello universe")
  • TrimPrefix(prefix string): Removes a specified prefix from the beginning of a string (e.g. "prefix-content" -> "content")
  • TrimSuffix(suffix string): Removes a specified suffix from the end of a string (e.g. "file.txt" -> "file")
  • Trim(): Removes spaces from the beginning and end of a string (e.g. " hello " -> "hello")
  • Contains(text, search string): Checks if a string contains another, returns boolean (e.g. Contains("hello world", "world") -> true)
  • CountOccurrences(text, search string): Counts how many times a string appears in another (e.g. CountOccurrences("hello hello world", "hello") -> 2)
  • Repeat(n int): Repeats the string n times (e.g. "abc".Repeat(3) -> "abcabcabc")
  • Truncate(maxWidth, reservedChars int): Truncates text to a specific width, adding ellipsis if necessary and padding with spaces if text is shorter (e.g. "Hello, World!".Truncate(10, 0) -> "Hello, ...")
Examples
// Remove accents
tinystring.Convert("áéíóú").RemoveTilde().String()
// Result: "aeiou"

// Convert to camelCase
tinystring.Convert("hello world").CamelCaseLower().String()
// Result: "helloWorld"

// Combining operations
tinystring.Convert("HÓLA MÚNDO")
    .RemoveTilde()
    .ToLower()
    .String()
// Result: "hola mundo"

// Converting different data types
tinystring.Convert(123).String()
// Result: "123"

tinystring.Convert(45.67).String()
// Result: "45.67"

tinystring.Convert(true).String()
// Result: "true"

// Convert and transform other data types
tinystring.Convert(456).CamelCaseUpper().String()
// Result: "456"

tinystring.Convert(false).ToUpper().String()
// Result: "FALSE"

// Split a string by separator
result := tinystring.Split("apple,banana,cherry", ",")
// Result: []string{"apple", "banana", "cherry"}

// Parse key-value string
value, err := tinystring.ParseKeyValue("user:admin")
// Result: value = "admin", err = nil

// Parse with custom delimiter
value, err := tinystring.ParseKeyValue("count=42", "=")
// Result: value = "42", err = nil

// Multiple values with same delimiter
value, err := tinystring.ParseKeyValue("path:usr:local:bin")
// Result: value = "usr:local:bin", err = nil

// Handle error when delimiter is not found
value, err := tinystring.ParseKeyValue("invalidstring")
// Result: value = "", err = error("delimiter ':' not found in string invalidstring")

// Replace text
tinystring.Convert("hello world").Replace("world", "universe").String()
// Result: "hello universe"

// Trim prefix and suffix
tinystring.Convert("prefix-content.txt").TrimPrefix("prefix-").TrimSuffix(".txt").String()
// Result: "content"

// Trim spaces and remove file extension
tinystring.Convert("  file.txt  ").Trim().TrimSuffix(".txt").String()
// Result: "file"

// Chain multiple operations
text := tinystring.Convert(" User Name ")
    .Trim()
    .Replace(" ", "_")
    .ToLower()
    .String()
// Result: "user_name"

// Search examples
// Check if a string contains another
result := tinystring.Contains("hello world", "world")
// Result: true

// Count occurrences
count := tinystring.CountOccurrences("abracadabra", "abra")
// Result: 2

// Capitalize each word
tinystring.Convert("hello world").Capitalize().String()
// Result: "Hello World"

// Capitalize with accent removal
tinystring.Convert("hólá múndo")
    .RemoveTilde()
    .Capitalize()
    .String()
// Result: "Hola Mundo"

// Repeat a string multiple times
tinystring.Convert("hello ").Repeat(3).String()
// Result: "hello hello hello "

// Repeat with other transformations
tinystring.Convert("test")
    .ToUpper()
    .Repeat(2)
    .String()
// Result: "TESTTEST"

// Zero or negative repetitions returns an empty string
tinystring.Convert("test").Repeat(0).String()
// Result: ""

// Truncate a long string to specific width
tinystring.Convert("Hello, World!").Truncate(10, 0).String()
// Result: "Hello, ..."

// Truncate with reserved characters
tinystring.Convert("Hello, World!").Truncate(10, 3).String()
// Result: "Hell..."

// Pad a short string with spaces
tinystring.Convert("Hello").Truncate(10, 0).String()
// Result: "Hello     "

// Truncate and transform
tinystring.Convert("hello world")
    .ToUpper()
    .Truncate(8, 0)
    .String()
// Result: "HELLO..."

// Chaining truncate and repeat
tinystring.Convert("hello")
    .Truncate(6, 0)
    .Repeat(2)
    .String()
// Result: "hello hello "

Contributing

Contributions are welcome. Please open an issue to discuss proposed changes.

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Contains added in v0.0.8

func Contains(text, search string) bool

Contains checks if the string 'search' is present in 'text' Returns true if found, false otherwise This matches the behavior of the standard library strings.Contains

func CountOccurrences added in v0.0.8

func CountOccurrences(text, search string) int

CountOccurrences checks how many times the string 'search' is present in 'text' eg: "hello world" with search "world" will return 1

func ParseKeyValue added in v0.0.10

func ParseKeyValue(input string, delimiters ...string) (value string, err error)

ParseKeyValue extracts the value part from a "key:value" formatted string. By default, it uses ":" as the delimiter but accepts an optional custom delimiter. The function returns the value part and an error (nil if successful).

Examples:

value, err := ParseKeyValue("name:John")
// value = "John", err = nil

value, err := ParseKeyValue("data=123", "=")
// value = "123", err = nil

value, err := ParseKeyValue("invalid-string")
// value = "", err = error containing "delimiter ':' not found in string invalid-string"

func Split added in v0.0.7

func Split(data, separator string) (result []string)

Split divides a string by a separator and returns a slice of substrings Note: Strings shorter than 3 characters are returned as is

Types

type Text

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

Text struct to store the content of the text

func Convert

func Convert(v any) *Text

initialize the text struct with any type of value supports string, int, float, bool and their variants

func (*Text) CamelCaseLower

func (t *Text) CamelCaseLower() *Text

converts text to camelCase (first word lowercase) eg: "Hello world" -> "helloWorld"

func (*Text) CamelCaseUpper

func (t *Text) CamelCaseUpper() *Text

converts text to PascalCase (all words capitalized) eg: "hello world" -> "HelloWorld"

func (*Text) Capitalize added in v0.0.11

func (t *Text) Capitalize() *Text

Capitalize transforms the first letter of each word to uppercase and the rest to lowercase. For example: "hello world" -> "Hello World"

func (*Text) RemoveTilde

func (t *Text) RemoveTilde() *Text

Remueve tildes y diacríticos

func (*Text) Repeat added in v0.0.13

func (t *Text) Repeat(n int) *Text

Repeat returns the string s repeated n times. If n is less than or equal to zero, or if s is empty, it returns an empty string. eg: Convert("abc").Repeat(3) => "abcabcabc"

func (*Text) Replace added in v0.0.7

func (t *Text) Replace(old, newStr string) *Text

Replace replaces all occurrences of old with new in the text content eg: "hello world" with old "world" and new "universe" will return "hello universe"

func (*Text) String

func (t *Text) String() string

String method to return the content of the text

func (*Text) ToLower

func (t *Text) ToLower() *Text

convert to lower case eg: "HELLO WORLD" -> "hello world"

func (*Text) ToSnakeCaseLower

func (t *Text) ToSnakeCaseLower(sep ...string) *Text

snakeCase converts a string to snake_case format with optional separator. If no separator is provided, underscore "_" is used as default. Example:

Input: "camelCase" -> Output: "camel_case"
Input: "PascalCase", "-" -> Output: "pascal-case"
Input: "APIResponse" -> Output: "api_response"
Input: "user123Name", "." -> Output: "user123.name"

ToSnakeCaseLower converts text to snake_case format

func (*Text) ToSnakeCaseUpper

func (t *Text) ToSnakeCaseUpper(sep ...string) *Text

ToSnakeCaseUpper converts text to Snake_Case format

func (*Text) ToUpper

func (t *Text) ToUpper() *Text

convert to upper case eg: "hello world" -> "HELLO WORLD"

func (*Text) Trim added in v0.0.7

func (t *Text) Trim() *Text

Trim removes spaces at the beginning and end of the text content eg: " hello world " will return "hello world"

func (*Text) TrimPrefix added in v0.0.9

func (t *Text) TrimPrefix(prefix string) *Text

TrimPrefix removes the specified prefix from the text content if it exists eg: "prefix-hello" with prefix "prefix-" will return "hello"

func (*Text) TrimSuffix added in v0.0.7

func (t *Text) TrimSuffix(suffix string) *Text

TrimSuffix removes the specified suffix from the text content if it exists eg: "hello.txt" with suffix ".txt" will return "hello"

func (*Text) Truncate added in v0.0.13

func (t *Text) Truncate(maxWidth int, reservedChars int) *Text

Truncate truncates a text so that it has exactly the specified width. If the text is longer, it truncates it and adds "..." if there is space. If the text is shorter, it pads it with spaces until the width is reached. The reservedChars parameter indicates how many characters should be reserved for suffixes. eg: Convert("Hello, World!").Truncate(10, 3) => "Hel..."

Jump to

Keyboard shortcuts

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