str

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 7 Imported by: 0

README

str logo

Fluent string helpers for Go.

Go Reference Go Test Go 1.24 or newer Latest tag Coverage Tests Go Report Card

str wraps a Go string so cleanup and transformation steps can be chained from left to right. Method names follow the standard library where possible, and operations that count, slice, or pad text work in runes rather than bytes.

Installation

Requires Go 1.24 or newer.

go get github.com/goforj/str/v2

Quick start

package main

import (
	"fmt"

	"github.com/goforj/str/v2"
)

func main() {
	result := str.Of("  welcome_to_go  ").Trim().Headline().String()
	fmt.Println(result) // Welcome to Go
}

API principles

str keeps the API deliberately small. These rules decide what belongs:

  • Chains come first. Start with str.Of. Methods that change text return a new str.String, so the chain can continue. Checks, counts, parsers, and splits return ordinary Go values.
  • One job, one name. There are no aliases or compatibility shims. If two names mean the same thing, keep the clearer one.
  • Use Go's words. When the standard library already names an operation, use the same name and argument order.
  • Work in runes. Character positions, counts, slices, padding, and case changes handle Unicode text instead of UTF-8 bytes unless the method says otherwise.
  • Do not hide edge cases. Empty searches do not match, replacing an empty search does nothing, and parsing or pattern errors are returned to the caller.
  • Every method earns its place. It must solve a common application problem or make a chain meaningfully clearer. Narrow, project-specific rules belong elsewhere.
  • Examples must keep working. Every public operation has a generated example, and the test suite runs each one and checks its output.

Why not just the standard library?

Often, you should. Go's strings, unicode, strconv, and regexp packages are the right choice when you only need one or two operations. This is already clear:

username := strings.ToLower(strings.TrimSpace("  GoForj_Admin  "))
// goforj_admin

The same cleanup with str reads from left to right:

username := str.Of("  GoForj_Admin  ").Trim().ToLower().String()
// goforj_admin

Either version is reasonable. The difference is easier to see when more rules belong together.

Using the standard library:

func configKey(name string) string {
	key := strings.TrimSpace(name)
	key = strings.ToUpper(key)
	key = strings.ReplaceAll(key, "-", "_")
	key = strings.Trim(key, "_")
	if !strings.HasPrefix(key, "APP_") {
		key = "APP_" + key
	}
	return key
}

// configKey("  --billing-worker--  ") == "APP_BILLING_WORKER"

Using str:

func configKey(name string) string {
	return str.Of(name).
		Trim().
		ToUpper().
		ReplaceAll("-", "_").
		TrimChars("_").
		EnsurePrefix("APP_").
		String()
}

// configKey("  --billing-worker--  ") == "APP_BILLING_WORKER"

Some jobs do not have a single standard library call. For example, Slug handles case, punctuation, repeated separators, and Unicode letters. It can be one step in a longer chain that turns a report title into a CSV filename with a 64-rune base name:

func exportFilename(reportTitle string) string {
	return str.Of(reportTitle).
		ReplaceAll("&", "and").
		Slug().
		Take(64).
		TrimChars("-").
		EnsurePrefix("report-").
		EnsureSuffix(".csv").
		String()
}

filename := exportFilename("Q3 Sales & Returns — North America")
// report-q3-sales-and-returns-north-america.csv

str uses the standard library underneath and has no dependencies. Use whichever version makes the rules easiest to see.

API index

The full API and these examples are also available on pkg.go.dev.

Group API
Affixes EnsurePrefix · EnsureSuffix · TrimPrefix · TrimSuffix · Unwrap · Wrap
Case Camel · Headline · Kebab · LcFirst · Pascal · Snake · Title · ToLower · ToUpper · UcFirst
Checks IsASCII · IsAlnum · IsAlpha · IsBlank · IsEmpty · IsNumeric
Cleanup Deduplicate · NormalizeNewlines · NormalizeSpace · Trim · TrimChars · TrimLeft · TrimRight
Comparison EqualFold
Compose Append · Prepend
Constructor Of
Conversion Bool · Float64 · Int
Encoding FromBase64 · ToBase64
Fluent GoString · String
Length RuneCount
Masking Mask
Match Match
Padding PadBoth · PadLeft · PadRight
Pluralize Plural · Singular
Replace Remove · ReplaceAll · ReplaceArray · ReplaceFirst · ReplaceFold · ReplaceLast · ReplacePrefix · ReplaceSuffix · Swap
Search Contains · ContainsFold · Count · HasPrefix · HasPrefixFold · HasSuffix · HasSuffixFold · Index · LastIndex
Slug Slug
Snippet Excerpt
Split Lines · Split
Substrings After · AfterLast · Before · BeforeLast · Between · CharAt · CommonPrefix · CommonSuffix · Limit · Slice · SubstrReplace · Take · TakeLast
Transform Repeat · Reverse
Words FirstWord · Initials · Join · LastWord · SplitWords · WordCount · Words · WrapWords

API examples

These examples come from GoDoc and run as part of the test suite.

Affixes

EnsurePrefix

EnsurePrefix ensures the string starts with prefix, adding it if missing. Similar: EnsureSuffix and TrimPrefix.

v := str.Of("path/to").EnsurePrefix("/").String()
println(v)
// #string /path/to
EnsureSuffix

EnsureSuffix ensures the string ends with suffix, adding it if missing. Similar: EnsurePrefix and TrimSuffix.

v := str.Of("path/to").EnsureSuffix("/").String()
println(v)
// #string path/to/
TrimPrefix

TrimPrefix removes prefix when it appears at the start of the string. Similar: TrimSuffix and EnsurePrefix.

v := str.Of("https://goforj.dev").TrimPrefix("https://").String()
println(v)
// #string goforj.dev
TrimSuffix

TrimSuffix removes suffix when it appears at the end of the string. Similar: TrimPrefix and EnsureSuffix.

v := str.Of("file.txt").TrimSuffix(".txt").String()
println(v)
// #string file
Unwrap

Unwrap removes matching before and after strings if present. Similar: Wrap.

v := str.Of(`"GoForj"`).Unwrap(`"`, `"`).String()
println(v)
// #string GoForj
Wrap

Wrap surrounds the string with before and after. Similar: Unwrap.

v := str.Of("GoForj").Wrap(`"`, `"`).String()
println(v)
// #string "GoForj"

Case

Camel

Camel converts the string to camelCase. Similar: Pascal.

v := str.Of("foo_bar baz").Camel().String()
println(v)
// #string fooBarBaz
Headline

Headline converts the string into a human-friendly headline: splits on case/underscores/dashes/whitespace, title-cases words, and lowercases small words (except the first). Similar: Title.

v := str.Of("emailNotification_sent").Headline().String()
println(v)
// #string Email Notification Sent
Kebab

Kebab converts the string to kebab-case. Similar: Snake.

v := str.Of("fooBar baz").Kebab().String()
println(v)
// #string foo-bar-baz
LcFirst

LcFirst returns the string with the first rune lower-cased. Similar: UcFirst and ToLower.

v := str.Of("Gopher").LcFirst().String()
fmt.Println(v)
// #string gopher
Pascal

Pascal converts the string to PascalCase. Similar: Camel.

v := str.Of("foo_bar baz").Pascal().String()
fmt.Println(v)
// #string FooBarBaz
Snake

Snake converts the string to snake_case. Similar: Kebab.

v := str.Of("fooBar baz").Snake().String()
println(v)
// #string foo_bar_baz
Title

Title converts the string to title case (first letter of each word upper, rest lower) using Unicode rules. Similar: Headline.

v := str.Of("a nice title uses the correct case").Title().String()
println(v)
// #string A Nice Title Uses The Correct Case
ToLower

ToLower returns a lowercase copy of the string using Unicode rules. Similar: ToUpper and LcFirst.

v := str.Of("GoLang").ToLower().String()
println(v)
// #string golang
ToUpper

ToUpper returns an uppercase copy of the string using Unicode rules. Similar: ToLower and UcFirst.

v := str.Of("GoLang").ToUpper().String()
println(v)
// #string GOLANG
UcFirst

UcFirst returns the string with the first rune upper-cased. Similar: LcFirst and ToUpper.

v := str.Of("gopher").UcFirst().String()
println(v)
// #string Gopher

Checks

IsASCII

IsASCII reports whether the string consists solely of 7-bit ASCII runes.

v := str.Of("gopher").IsASCII()
println(v)
// #bool true
IsAlnum

IsAlnum reports whether the string contains at least one rune and every rune is a Unicode letter or number.

v := str.Of("Gopher2025").IsAlnum()
println(v)
// #bool true
IsAlpha

IsAlpha reports whether the string contains at least one rune and every rune is a Unicode letter.

v := str.Of("Gopher").IsAlpha()
println(v)
// #bool true
IsBlank

IsBlank reports whether the string contains only Unicode whitespace. Similar: IsEmpty.

v := str.Of("  \t\n")
println(v.IsBlank())
// #bool true
IsEmpty

IsEmpty reports whether the string has zero length. Similar: IsBlank.

v := str.Of("").IsEmpty()
println(v)
// #bool true
IsNumeric

IsNumeric reports whether the string contains at least one rune and every rune is a Unicode number.

v := str.Of("12345").IsNumeric()
println(v)
// #bool true

Cleanup

Deduplicate

Deduplicate collapses consecutive instances of char into a single instance. If char is zero, space is used. Similar: NormalizeSpace.

v := str.Of("The   Go   Playground").Deduplicate(' ').String()
println(v)
// #string The Go Playground
NormalizeNewlines

NormalizeNewlines replaces CRLF, CR, and Unicode separators with \n. Similar: Lines.

v := str.Of("a\r\nb\u2028c").NormalizeNewlines().String()
println(v)
// #string a\nb\nc
NormalizeSpace

NormalizeSpace removes surrounding whitespace and collapses internal whitespace to single spaces. Similar: Trim.

v := str.Of("  go   forj  ").NormalizeSpace().String()
println(v)
// #string go forj
Trim

Trim removes leading and trailing Unicode whitespace. Similar: TrimLeft, TrimRight, and TrimChars.

v := str.Of("  GoForj  ").Trim().String()
println(v)
// #string GoForj
TrimChars

TrimChars removes leading and trailing runes contained in cutset. Similar: Trim.

v := str.Of("..GoForj!!").TrimChars(".!").String()
println(v)
// #string GoForj
TrimLeft

TrimLeft removes leading Unicode whitespace. Similar: Trim and TrimRight.

v := str.Of("  GoForj  ").TrimLeft().String()
println(v)
// #string GoForj\u0020\u0020
TrimRight

TrimRight removes trailing Unicode whitespace. Similar: Trim and TrimLeft.

v := str.Of("  GoForj  ").TrimRight().String()
println(v)
// #string \u0020\u0020GoForj

Comparison

EqualFold

EqualFold reports whether the string matches other using Unicode simple case folding.

v := str.Of("gopher").EqualFold("GOPHER")
println(v)
// #bool true

Compose

Append

Append concatenates the provided parts to the end of the string. Similar: Prepend.

v := str.Of("Go").Append("Forj", "!").String()
println(v)
// #string GoForj!
Prepend

Prepend concatenates the provided parts to the beginning of the string. Similar: Append.

v := str.Of("World").Prepend("Hello ", "Go ").String()
println(v)
// #string Hello Go World

Constructor

Of

Of wraps a raw string with fluent helpers.

v := str.Of("gopher")
println(v.String())
// #string gopher

Conversion

Bool

Bool parses the string as a bool using strconv.ParseBool semantics. Similar: Int and Float64.

v, err := str.Of("true").Bool()
println(v, err == nil)
// #bool true
// #bool true
Float64

Float64 parses the string as a float64 using strconv.ParseFloat semantics. Similar: Bool and Int.

v, err := str.Of("3.14").Float64()
fmt.Println(v, err == nil)
// #float64 3.14
// #bool true
Int

Int parses the string as a base-10 int using strconv.Atoi semantics. Similar: Bool and Float64.

v, err := str.Of("42").Int()
println(v, err == nil)
// #int 42
// #bool true

Encoding

FromBase64

FromBase64 decodes a standard Base64 string. Similar: ToBase64.

v, err := str.Of("Z29waGVy").FromBase64()
println(v.String(), err == nil)
// #string gopher
// #bool true
ToBase64

ToBase64 encodes the string using standard Base64. Similar: FromBase64.

v := str.Of("gopher").ToBase64().String()
println(v)
// #string Z29waGVy

Fluent

GoString

GoString allows %#v formatting to print the raw string.

v := str.Of("go")
println(fmt.Sprintf("%#v", v))
// #string go
String

String returns the underlying raw string value.

v := str.Of("go").String()
println(v)
// #string go

Length

RuneCount

RuneCount returns the number of Unicode code points in the string.

v := str.Of("gophers 🦫").RuneCount()
println(v)
// #int 9

Masking

Mask

Mask replaces the middle of the string with the given rune, revealing revealLeft runes at the start and revealRight runes at the end. Negative reveal values count from the end. If the reveal counts cover the whole string, the original string is returned.

v := str.Of("gopher@example.com").Mask('*', 3, 4).String()
println(v)
// #string gop***********.com

Match

Match

Match reports whether the entire string matches pattern using [path.Match] syntax. A malformed pattern returns an error, and wildcards do not match a slash.

matched, err := str.Of("billing:reports").Match("billing:*")
println(matched, err == nil)
// #bool true
// #bool true

Padding

PadBoth

PadBoth pads the string on both sides to reach length runes using pad (defaults to space). Widths at or below the current rune width leave the string unchanged. Similar: PadLeft and PadRight.

v := str.Of("go").PadBoth(6, "-").String()
println(v)
// #string --go--
PadLeft

PadLeft pads the string on the left to reach length runes using pad (defaults to space). Widths at or below the current rune width leave the string unchanged. Similar: PadRight and PadBoth.

v := str.Of("go").PadLeft(5, " ").String()
println(v)
// #string \u0020\u0020\u0020go
PadRight

PadRight pads the string on the right to reach length runes using pad (defaults to space). Widths at or below the current rune width leave the string unchanged. Similar: PadLeft and PadBoth.

v := str.Of("go").PadRight(5, ".").String()
println(v)
// #string go...

Pluralize

Plural

Plural returns a best-effort English plural form of the final identifier word. It handles common English forms and identifier boundaries without claiming to resolve every irregular or ambiguous noun. Similar: Singular.

v := str.Of("city").Plural().String()
println(v)
// #string cities
Singular

Singular returns a best-effort English singular form of the final identifier word. It handles common English forms and identifier boundaries without claiming to resolve every irregular or ambiguous noun. Similar: Plural.

v := str.Of("people").Singular().String()
println(v)
// #string person

Replace

Remove

Remove deletes all occurrences of provided substrings.

v := str.Of("The Go Toolkit").Remove("Go ").String()
println(v)
// #string The Toolkit
ReplaceAll

ReplaceAll replaces all occurrences of old with new in the string. If old is empty, the original string is returned unchanged.

v := str.Of("go gopher go").ReplaceAll("go", "Go").String()
println(v)
// #string Go Gopher Go
ReplaceArray

ReplaceArray replaces all occurrences of each old in olds with repl. Similar: ReplaceAll and Swap.

v := str.Of("The---Go---Toolkit")
println(v.ReplaceArray([]string{"---"}, "-").String())
// #string The-Go-Toolkit
ReplaceFirst

ReplaceFirst replaces the first occurrence of old with repl. Similar: ReplaceLast and ReplaceAll.

v := str.Of("gopher gopher").ReplaceFirst("gopher", "go").String()
println(v)
// #string go gopher
ReplaceFold

ReplaceFold replaces all non-overlapping occurrences of old with repl using Unicode simple case folding. An empty old string leaves the receiver unchanged. Similar: ReplaceAll.

v := str.Of("go gopher GO").ReplaceFold("GO", "Go").String()
println(v)
// #string Go Gopher Go
ReplaceLast

ReplaceLast replaces the last occurrence of old with repl. Similar: ReplaceFirst and ReplaceAll.

v := str.Of("gopher gopher").ReplaceLast("gopher", "go").String()
println(v)
// #string gopher go
ReplacePrefix

ReplacePrefix replaces old with repl when old is a prefix of the string. Similar: ReplaceSuffix and TrimPrefix.

v := str.Of("prefix-value").ReplacePrefix("prefix-", "new-").String()
println(v)
// #string new-value
ReplaceSuffix

ReplaceSuffix replaces old with repl when old is a suffix of the string. Similar: ReplacePrefix and TrimSuffix.

v := str.Of("file.old").ReplaceSuffix(".old", ".new").String()
println(v)
// #string file.new
Swap

Swap replaces multiple values using strings.Replacer built from a map. Similar: ReplaceArray.

pairs := map[string]string{"Gophers": "GoForj", "are": "is", "great": "fantastic"}
v := str.Of("Gophers are great!").Swap(pairs).String()
println(v)
// #string GoForj is fantastic!
Contains

Contains reports whether the string contains sub using a case-sensitive comparison. An empty substring is not a match. Similar: ContainsFold.

v := str.Of("Go means gophers").Contains("gopher")
println(v)
// #bool true
ContainsFold

ContainsFold reports whether the string contains sub using Unicode simple case folding. An empty substring is not a match. Similar: Contains.

v := str.Of("Go means gophers").ContainsFold("GOPHER")
println(v)
// #bool true
Count

Count returns the number of non-overlapping occurrences of sub.

v := str.Of("gogophergo").Count("go")
println(v)
// #int 3
HasPrefix

HasPrefix reports whether the string starts with prefix using a case-sensitive comparison. An empty prefix is not a match. Similar: HasPrefixFold and HasSuffix.

v := str.Of("gopher").HasPrefix("go")
println(v)
// #bool true
HasPrefixFold

HasPrefixFold reports whether the string starts with prefix using Unicode simple case folding. An empty prefix is not a match. Similar: HasPrefix and HasSuffixFold.

v := str.Of("gopher").HasPrefixFold("GO")
println(v)
// #bool true
HasSuffix

HasSuffix reports whether the string ends with suffix using a case-sensitive comparison. An empty suffix is not a match. Similar: HasSuffixFold and HasPrefix.

v := str.Of("gopher").HasSuffix("her")
println(v)
// #bool true
HasSuffixFold

HasSuffixFold reports whether the string ends with suffix using Unicode simple case folding. An empty suffix is not a match. Similar: HasSuffix and HasPrefixFold.

v := str.Of("gopher").HasSuffixFold("HER")
println(v)
// #bool true
Index

Index returns the rune index of the first occurrence of sub, or -1 if not found. Similar: LastIndex.

v := str.Of("héllo").Index("llo")
println(v)
// #int 2
LastIndex

LastIndex returns the rune index of the last occurrence of sub, or -1 if not found. Similar: Index.

v := str.Of("go gophers go").LastIndex("go")
println(v)
// #int 11

Slug

Slug

Slug returns a lowercase Unicode slug separated by hyphens. Unicode letters and digits are preserved, while every other run is collapsed to one hyphen. Similar: Kebab.

v := str.Of("Go Forj Toolkit").Slug().String()
println(v)
// #string go-forj-toolkit

Snippet

Excerpt

Excerpt returns a snippet around the first occurrence of needle with the given radius. If needle is not found, an empty string is returned. If radius <= 0, a default of 100 is used. Omission is used at the start/end when text is trimmed (default "...").

v := str.Of("This is my name").Excerpt("my", 3, "...")
println(v.String())
// #string ...is my na...

Split

Lines

Lines splits the string into lines after normalizing newline variants. Similar: NormalizeNewlines.

v := str.Of("a\r\nb\nc").Lines()
fmt.Println(v)
// #[]string [a b c]
Split

Split splits the string by the given separator.

v := str.Of("a,b,c").Split(",")
fmt.Println(v)
// #[]string [a b c]

Substrings

After

After returns the substring after the first occurrence of sep. If sep is empty or not found, the original string is returned. Similar: AfterLast and Before.

v := str.Of("gopher::go").After("::").String()
println(v)
// #string go
AfterLast

AfterLast returns the substring after the last occurrence of sep. If sep is empty or not found, the original string is returned. Similar: After and BeforeLast.

v := str.Of("pkg/path/file.txt").AfterLast("/").String()
println(v)
// #string file.txt
Before

Before returns the substring before the first occurrence of sep. If sep is empty or not found, the original string is returned. Similar: BeforeLast and After.

v := str.Of("gopher::go").Before("::").String()
println(v)
// #string gopher
BeforeLast

BeforeLast returns the substring before the last occurrence of sep. If sep is empty or not found, the original string is returned. Similar: Before and AfterLast.

v := str.Of("pkg/path/file.txt").BeforeLast("/").String()
println(v)
// #string pkg/path
Between

Between returns the substring between the first start marker and the first end marker after it. It returns an empty string when either marker is empty or missing.

v := str.Of("[first] and [second]").Between("[", "]").String()
println(v)
// #string first
CharAt

CharAt returns the rune at the given index and true if within bounds. Similar: Slice and RuneCount.

v, ok := str.Of("gopher").CharAt(2)
println(string(v), ok)
// #string p
// #bool true
CommonPrefix

CommonPrefix returns the longest shared prefix between the string and all provided others. Comparison is rune-safe. If no others are provided, the original string is returned. Similar: CommonSuffix.

v := str.Of("gopher").CommonPrefix("go", "gold").String()
println(v)
// #string go
CommonSuffix

CommonSuffix returns the longest shared suffix between the string and all provided others. Comparison is rune-safe. If no others are provided, the original string is returned. Similar: CommonPrefix.

v := str.Of("main_test.go").CommonSuffix("user_test.go", "api_test.go").String()
println(v)
// #string _test.go
Limit

Limit truncates the string to length runes, appending suffix if truncation occurs.

v := str.Of("Perfectly balanced, as all things should be.").Limit(10, "...").String()
println(v)
// #string Perfectly\u0020...
Slice

Slice returns the substring between rune offsets [start:end). Indices are clamped; if start >= end the result is empty.

v := str.Of("naïve café").Slice(3, 7).String()
println(v)
// #string ve c
SubstrReplace

SubstrReplace replaces the rune slice in [start:end) with repl.

v := str.Of("naïve café").SubstrReplace("i", 2, 3).String()
println(v)
// #string naive café
Take

Take returns the first length runes of the string (clamped). Similar: TakeLast and Limit.

v := str.Of("gophers").Take(3).String()
println(v)
// #string gop
TakeLast

TakeLast returns the last length runes of the string (clamped). Similar: Take.

v := str.Of("gophers").TakeLast(4).String()
println(v)
// #string hers

Transform

Repeat

Repeat repeats the string count times (non-negative).

v := str.Of("go").Repeat(3).String()
println(v)
// #string gogogo
Reverse

Reverse returns a rune-safe reversed string.

v := str.Of("naïve").Reverse().String()
println(v)
// #string evïan

Words

FirstWord

FirstWord returns the first detected word or an empty string. Similar: LastWord and SplitWords.

v := str.Of("Hello world")
println(v.FirstWord().String())
// #string Hello
Initials

Initials returns the uppercase first rune of each detected word. Words are split the same way as SplitWords, including camel case and acronym boundaries. Similar: SplitWords.

v := str.Of("portableNetwork graphics").Initials().String()
println(v)
// #string PNG
Join

Join concatenates elements with sep and returns the result to the fluent chain. The receiver provides fluent access and is not included in elements. Similar: Split.

v := str.Of("").Join([]string{"foo", "bar"}, "-").String()
println(v)
// #string foo-bar
LastWord

LastWord returns the last detected word or an empty string. Similar: FirstWord and SplitWords.

v := str.Of("Hello world").LastWord().String()
println(v)
// #string world
SplitWords

SplitWords splits the string into Unicode words, including camel case and acronym boundaries. Similar: FirstWord, LastWord, WordCount, and Words.

v := str.Of("one, two, three").SplitWords()
fmt.Println(v)
// #[]string [one two three]
WordCount

WordCount returns the number of detected words. Similar: SplitWords.

v := str.Of("Hello, world!").WordCount()
println(v)
// #int 2
Words

Words limits the string to count words, preserving the source through the selected word boundary and appending suffix if truncated. Similar: SplitWords and WrapWords.

v := str.Of("Perfectly balanced, as all things should be.").Words(3, " >>>").String()
println(v)
// #string Perfectly balanced, as >>>
WrapWords

WrapWords wraps the string to the given rune width on whitespace boundaries, using breakStr between lines without discarding punctuation. Similar: Words.

v := str.Of("The quick brown fox jumped over the lazy dog.").WrapWords(20, "\n").String()
println(v)
// #string The quick brown fox\njumped over the lazy\ndog.

Documentation

Development

docs and examples are separate Go modules, keeping their tooling and generated programs out of the library module download.

Run the tests and rebuild the generated examples and README with:

go test ./...
go -C docs test ./...
go -C examples test ./...
go -C docs run ./examplegen
go -C docs run ./readme

Licensed under the MIT License.

Documentation

Overview

Package str provides an immutable fluent wrapper for practical Unicode-aware string operations that are awkward or repetitive with Go's standard library.

Names follow the Go standard library where an equivalent concept exists. Empty search terms are treated as no match, replacement operations are no-ops for empty search terms, and positions, lengths, and widths are measured in Unicode code points unless a method explicitly documents otherwise.

String is intended for short-lived transformation chains. Call String.String to store or serialize the resulting built-in string value.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type String

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

String is an immutable wrapper for fluent string operations. @group Fluent

func Of

func Of(s string) String

Of wraps a raw string with fluent helpers. @group Constructor

Example: wrap raw string

v := str.Of("gopher")
println(v.String())
// #string gopher

func (String) After

func (s String) After(sep string) String

After returns the substring after the first occurrence of sep. If sep is empty or not found, the original string is returned. Similar: AfterLast and Before. @group Substrings

Example: slice after marker

v := str.Of("gopher::go").After("::").String()
println(v)
// #string go

func (String) AfterLast

func (s String) AfterLast(sep string) String

AfterLast returns the substring after the last occurrence of sep. If sep is empty or not found, the original string is returned. Similar: After and BeforeLast. @group Substrings

Example: slice after last separator

v := str.Of("pkg/path/file.txt").AfterLast("/").String()
println(v)
// #string file.txt

func (String) Append

func (s String) Append(parts ...string) String

Append concatenates the provided parts to the end of the string. Similar: Prepend. @group Compose

Example: append text

v := str.Of("Go").Append("Forj", "!").String()
println(v)
// #string GoForj!

func (String) Before

func (s String) Before(sep string) String

Before returns the substring before the first occurrence of sep. If sep is empty or not found, the original string is returned. Similar: BeforeLast and After. @group Substrings

Example: slice before marker

v := str.Of("gopher::go").Before("::").String()
println(v)
// #string gopher

func (String) BeforeLast

func (s String) BeforeLast(sep string) String

BeforeLast returns the substring before the last occurrence of sep. If sep is empty or not found, the original string is returned. Similar: Before and AfterLast. @group Substrings

Example: slice before last separator

v := str.Of("pkg/path/file.txt").BeforeLast("/").String()
println(v)
// #string pkg/path

func (String) Between

func (s String) Between(start, end string) String

Between returns the substring between the first start marker and the first end marker after it. It returns an empty string when either marker is empty or missing. @group Substrings

Example: between markers

v := str.Of("[first] and [second]").Between("[", "]").String()
println(v)
// #string first

func (String) Bool

func (s String) Bool() (bool, error)

Bool parses the string as a bool using strconv.ParseBool semantics. Similar: Int and Float64. @group Conversion

Example: parse bool

v, err := str.Of("true").Bool()
println(v, err == nil)
// #bool true
// #bool true

func (String) Camel

func (s String) Camel() String

Camel converts the string to camelCase. Similar: Pascal. @group Case

Example: camel case

v := str.Of("foo_bar baz").Camel().String()
println(v)
// #string fooBarBaz

func (String) CharAt

func (s String) CharAt(idx int) (rune, bool)

CharAt returns the rune at the given index and true if within bounds. Similar: Slice and RuneCount. @group Substrings

Example: rune lookup

v, ok := str.Of("gopher").CharAt(2)
println(string(v), ok)
// #string p
// #bool true

func (String) CommonPrefix

func (s String) CommonPrefix(others ...string) String

CommonPrefix returns the longest shared prefix between the string and all provided others. Comparison is rune-safe. If no others are provided, the original string is returned. Similar: CommonSuffix. @group Substrings

Example: longest common prefix

v := str.Of("gopher").CommonPrefix("go", "gold").String()
println(v)
// #string go

func (String) CommonSuffix

func (s String) CommonSuffix(others ...string) String

CommonSuffix returns the longest shared suffix between the string and all provided others. Comparison is rune-safe. If no others are provided, the original string is returned. Similar: CommonPrefix. @group Substrings

Example: longest common suffix

v := str.Of("main_test.go").CommonSuffix("user_test.go", "api_test.go").String()
println(v)
// #string _test.go

func (String) Contains

func (s String) Contains(sub string) bool

Contains reports whether the string contains sub using a case-sensitive comparison. An empty substring is not a match. Similar: ContainsFold. @group Search

Example: contains substring

v := str.Of("Go means gophers").Contains("gopher")
println(v)
// #bool true

func (String) ContainsFold

func (s String) ContainsFold(sub string) bool

ContainsFold reports whether the string contains sub using Unicode simple case folding. An empty substring is not a match. Similar: Contains. @group Search

Example: contains substring (case-insensitive)

v := str.Of("Go means gophers").ContainsFold("GOPHER")
println(v)
// #bool true

func (String) Count

func (s String) Count(sub string) int

Count returns the number of non-overlapping occurrences of sub. @group Search

Example: count substring

v := str.Of("gogophergo").Count("go")
println(v)
// #int 3

func (String) Deduplicate

func (s String) Deduplicate(char rune) String

Deduplicate collapses consecutive instances of char into a single instance. If char is zero, space is used. Similar: NormalizeSpace. @group Cleanup

Example: collapse spaces

v := str.Of("The   Go   Playground").Deduplicate(' ').String()
println(v)
// #string The Go Playground

func (String) EnsurePrefix

func (s String) EnsurePrefix(prefix string) String

EnsurePrefix ensures the string starts with prefix, adding it if missing. Similar: EnsureSuffix and TrimPrefix. @group Affixes

Example: ensure prefix

v := str.Of("path/to").EnsurePrefix("/").String()
println(v)
// #string /path/to

func (String) EnsureSuffix

func (s String) EnsureSuffix(suffix string) String

EnsureSuffix ensures the string ends with suffix, adding it if missing. Similar: EnsurePrefix and TrimSuffix. @group Affixes

Example: ensure suffix

v := str.Of("path/to").EnsureSuffix("/").String()
println(v)
// #string path/to/

func (String) EqualFold

func (s String) EqualFold(other string) bool

EqualFold reports whether the string matches other using Unicode simple case folding. @group Comparison

Example: case-insensitive match

v := str.Of("gopher").EqualFold("GOPHER")
println(v)
// #bool true

func (String) Excerpt

func (s String) Excerpt(needle string, radius int, omission string) String

Excerpt returns a snippet around the first occurrence of needle with the given radius. If needle is not found, an empty string is returned. If radius <= 0, a default of 100 is used. Omission is used at the start/end when text is trimmed (default "..."). @group Snippet

Example: excerpt with radius

v := str.Of("This is my name").Excerpt("my", 3, "...")
println(v.String())
// #string ...is my na...

func (String) FirstWord

func (s String) FirstWord() String

FirstWord returns the first detected word or an empty string. Similar: LastWord and SplitWords. @group Words

Example: first word

v := str.Of("Hello world")
println(v.FirstWord().String())
// #string Hello

func (String) Float64

func (s String) Float64() (float64, error)

Float64 parses the string as a float64 using strconv.ParseFloat semantics. Similar: Bool and Int. @group Conversion

Example: parse float64

v, err := str.Of("3.14").Float64()
fmt.Println(v, err == nil)
// #float64 3.14
// #bool true

func (String) FromBase64

func (s String) FromBase64() (String, error)

FromBase64 decodes a standard Base64 string. Similar: ToBase64. @group Encoding

Example: base64 decode

v, err := str.Of("Z29waGVy").FromBase64()
println(v.String(), err == nil)
// #string gopher
// #bool true

func (String) GoString

func (s String) GoString() string

GoString allows %#v formatting to print the raw string. @group Fluent

Example: fmt %#v uses GoString

v := str.Of("go")
println(fmt.Sprintf("%#v", v))
// #string go

func (String) HasPrefix

func (s String) HasPrefix(prefix string) bool

HasPrefix reports whether the string starts with prefix using a case-sensitive comparison. An empty prefix is not a match. Similar: HasPrefixFold and HasSuffix. @group Search

Example: has prefix

v := str.Of("gopher").HasPrefix("go")
println(v)
// #bool true

func (String) HasPrefixFold

func (s String) HasPrefixFold(prefix string) bool

HasPrefixFold reports whether the string starts with prefix using Unicode simple case folding. An empty prefix is not a match. Similar: HasPrefix and HasSuffixFold. @group Search

Example: has prefix (case-insensitive)

v := str.Of("gopher").HasPrefixFold("GO")
println(v)
// #bool true

func (String) HasSuffix

func (s String) HasSuffix(suffix string) bool

HasSuffix reports whether the string ends with suffix using a case-sensitive comparison. An empty suffix is not a match. Similar: HasSuffixFold and HasPrefix. @group Search

Example: has suffix

v := str.Of("gopher").HasSuffix("her")
println(v)
// #bool true

func (String) HasSuffixFold

func (s String) HasSuffixFold(suffix string) bool

HasSuffixFold reports whether the string ends with suffix using Unicode simple case folding. An empty suffix is not a match. Similar: HasSuffix and HasPrefixFold. @group Search

Example: has suffix (case-insensitive)

v := str.Of("gopher").HasSuffixFold("HER")
println(v)
// #bool true

func (String) Headline

func (s String) Headline() String

Headline converts the string into a human-friendly headline: splits on case/underscores/dashes/whitespace, title-cases words, and lowercases small words (except the first). Similar: Title. @group Case

Example: headline

v := str.Of("emailNotification_sent").Headline().String()
println(v)
// #string Email Notification Sent

func (String) Index

func (s String) Index(sub string) int

Index returns the rune index of the first occurrence of sub, or -1 if not found. Similar: LastIndex. @group Search

Example: first rune index

v := str.Of("héllo").Index("llo")
println(v)
// #int 2

func (String) Initials

func (s String) Initials() String

Initials returns the uppercase first rune of each detected word. Words are split the same way as SplitWords, including camel case and acronym boundaries. Similar: SplitWords. @group Words

Example: collect word initials

v := str.Of("portableNetwork graphics").Initials().String()
println(v)
// #string PNG

func (String) Int

func (s String) Int() (int, error)

Int parses the string as a base-10 int using strconv.Atoi semantics. Similar: Bool and Float64. @group Conversion

Example: parse int

v, err := str.Of("42").Int()
println(v, err == nil)
// #int 42
// #bool true

func (String) IsASCII

func (s String) IsASCII() bool

IsASCII reports whether the string consists solely of 7-bit ASCII runes. @group Checks

Example: ASCII check

v := str.Of("gopher").IsASCII()
println(v)
// #bool true

func (String) IsAlnum

func (s String) IsAlnum() bool

IsAlnum reports whether the string contains at least one rune and every rune is a Unicode letter or number. @group Checks

Example: alphanumeric check

v := str.Of("Gopher2025").IsAlnum()
println(v)
// #bool true

func (String) IsAlpha

func (s String) IsAlpha() bool

IsAlpha reports whether the string contains at least one rune and every rune is a Unicode letter. @group Checks

Example: alphabetic check

v := str.Of("Gopher").IsAlpha()
println(v)
// #bool true

func (String) IsBlank

func (s String) IsBlank() bool

IsBlank reports whether the string contains only Unicode whitespace. Similar: IsEmpty. @group Checks

Example: blank check

v := str.Of("  \t\n")
println(v.IsBlank())
// #bool true

func (String) IsEmpty

func (s String) IsEmpty() bool

IsEmpty reports whether the string has zero length. Similar: IsBlank. @group Checks

Example: empty check

v := str.Of("").IsEmpty()
println(v)
// #bool true

func (String) IsNumeric

func (s String) IsNumeric() bool

IsNumeric reports whether the string contains at least one rune and every rune is a Unicode number. @group Checks

Example: numeric check

v := str.Of("12345").IsNumeric()
println(v)
// #bool true

func (String) Join

func (s String) Join(elements []string, sep string) String

Join concatenates elements with sep and returns the result to the fluent chain. The receiver provides fluent access and is not included in elements. Similar: Split. @group Words

Example: join words

v := str.Of("").Join([]string{"foo", "bar"}, "-").String()
println(v)
// #string foo-bar

func (String) Kebab

func (s String) Kebab() String

Kebab converts the string to kebab-case. Similar: Snake. @group Case

Example: kebab case

v := str.Of("fooBar baz").Kebab().String()
println(v)
// #string foo-bar-baz

func (String) LastIndex

func (s String) LastIndex(sub string) int

LastIndex returns the rune index of the last occurrence of sub, or -1 if not found. Similar: Index. @group Search

Example: last rune index

v := str.Of("go gophers go").LastIndex("go")
println(v)
// #int 11

func (String) LastWord

func (s String) LastWord() String

LastWord returns the last detected word or an empty string. Similar: FirstWord and SplitWords. @group Words

Example: last word

v := str.Of("Hello world").LastWord().String()
println(v)
// #string world

func (String) LcFirst

func (s String) LcFirst() String

LcFirst returns the string with the first rune lower-cased. Similar: UcFirst and ToLower. @group Case

Example: lowercase first rune

v := str.Of("Gopher").LcFirst().String()
fmt.Println(v)
// #string gopher

func (String) Limit

func (s String) Limit(length int, suffix string) String

Limit truncates the string to length runes, appending suffix if truncation occurs. @group Substrings

Example: limit with suffix

v := str.Of("Perfectly balanced, as all things should be.").Limit(10, "...").String()
println(v)
// #string Perfectly\u0020...

func (String) Lines

func (s String) Lines() []string

Lines splits the string into lines after normalizing newline variants. Similar: NormalizeNewlines. @group Split

Example: split lines

v := str.Of("a\r\nb\nc").Lines()
fmt.Println(v)
// #[]string [a b c]

func (String) Mask

func (s String) Mask(mask rune, revealLeft, revealRight int) String

Mask replaces the middle of the string with the given rune, revealing revealLeft runes at the start and revealRight runes at the end. Negative reveal values count from the end. If the reveal counts cover the whole string, the original string is returned. @group Masking

Example: mask email

v := str.Of("gopher@example.com").Mask('*', 3, 4).String()
println(v)
// #string gop***********.com

func (String) Match

func (s String) Match(pattern string) (bool, error)

Match reports whether the entire string matches pattern using path.Match syntax. A malformed pattern returns an error, and wildcards do not match a slash. @group Match

Example: match a shell pattern

matched, err := str.Of("billing:reports").Match("billing:*")
println(matched, err == nil)
// #bool true
// #bool true

func (String) NormalizeNewlines

func (s String) NormalizeNewlines() String

NormalizeNewlines replaces CRLF, CR, and Unicode separators with \n. Similar: Lines. @group Cleanup

Example: normalize newline variants

v := str.Of("a\r\nb\u2028c").NormalizeNewlines().String()
println(v)
// #string a\nb\nc

func (String) NormalizeSpace

func (s String) NormalizeSpace() String

NormalizeSpace removes surrounding whitespace and collapses internal whitespace to single spaces. Similar: Trim. @group Cleanup

Example: normalize whitespace

v := str.Of("  go   forj  ").NormalizeSpace().String()
println(v)
// #string go forj

func (String) PadBoth

func (s String) PadBoth(length int, pad string) String

PadBoth pads the string on both sides to reach length runes using pad (defaults to space). Widths at or below the current rune width leave the string unchanged. Similar: PadLeft and PadRight. @group Padding

Example: pad both

v := str.Of("go").PadBoth(6, "-").String()
println(v)
// #string --go--

func (String) PadLeft

func (s String) PadLeft(length int, pad string) String

PadLeft pads the string on the left to reach length runes using pad (defaults to space). Widths at or below the current rune width leave the string unchanged. Similar: PadRight and PadBoth. @group Padding

Example: pad left

v := str.Of("go").PadLeft(5, " ").String()
println(v)
// #string \u0020\u0020\u0020go

func (String) PadRight

func (s String) PadRight(length int, pad string) String

PadRight pads the string on the right to reach length runes using pad (defaults to space). Widths at or below the current rune width leave the string unchanged. Similar: PadLeft and PadBoth. @group Padding

Example: pad right

v := str.Of("go").PadRight(5, ".").String()
println(v)
// #string go...

func (String) Pascal

func (s String) Pascal() String

Pascal converts the string to PascalCase. Similar: Camel. @group Case

Example: pascal case

v := str.Of("foo_bar baz").Pascal().String()
fmt.Println(v)
// #string FooBarBaz

func (String) Plural

func (s String) Plural() String

Plural returns a best-effort English plural form of the final identifier word. It handles common English forms and identifier boundaries without claiming to resolve every irregular or ambiguous noun. Similar: Singular. @group Pluralize

Example: pluralize word

v := str.Of("city").Plural().String()
println(v)
// #string cities

func (String) Prepend

func (s String) Prepend(parts ...string) String

Prepend concatenates the provided parts to the beginning of the string. Similar: Append. @group Compose

Example: prepend text

v := str.Of("World").Prepend("Hello ", "Go ").String()
println(v)
// #string Hello Go World

func (String) Remove

func (s String) Remove(subs ...string) String

Remove deletes all occurrences of provided substrings. @group Replace

Example: remove substrings

v := str.Of("The Go Toolkit").Remove("Go ").String()
println(v)
// #string The Toolkit

func (String) Repeat

func (s String) Repeat(count int) String

Repeat repeats the string count times (non-negative). @group Transform

Example: repeat string

v := str.Of("go").Repeat(3).String()
println(v)
// #string gogogo

func (String) ReplaceAll

func (s String) ReplaceAll(old, new string) String

ReplaceAll replaces all occurrences of old with new in the string. If old is empty, the original string is returned unchanged. @group Replace

Example: replace all occurrences

v := str.Of("go gopher go").ReplaceAll("go", "Go").String()
println(v)
// #string Go Gopher Go

func (String) ReplaceArray

func (s String) ReplaceArray(olds []string, repl string) String

ReplaceArray replaces all occurrences of each old in olds with repl. Similar: ReplaceAll and Swap. @group Replace

Example: replace many

v := str.Of("The---Go---Toolkit")
println(v.ReplaceArray([]string{"---"}, "-").String())
// #string The-Go-Toolkit

func (String) ReplaceFirst

func (s String) ReplaceFirst(old, repl string) String

ReplaceFirst replaces the first occurrence of old with repl. Similar: ReplaceLast and ReplaceAll. @group Replace

Example: replace first

v := str.Of("gopher gopher").ReplaceFirst("gopher", "go").String()
println(v)
// #string go gopher

func (String) ReplaceFold

func (s String) ReplaceFold(old, repl string) String

ReplaceFold replaces all non-overlapping occurrences of old with repl using Unicode simple case folding. An empty old string leaves the receiver unchanged. Similar: ReplaceAll. @group Replace

Example: replace all (case-insensitive)

v := str.Of("go gopher GO").ReplaceFold("GO", "Go").String()
println(v)
// #string Go Gopher Go

func (String) ReplaceLast

func (s String) ReplaceLast(old, repl string) String

ReplaceLast replaces the last occurrence of old with repl. Similar: ReplaceFirst and ReplaceAll. @group Replace

Example: replace last

v := str.Of("gopher gopher").ReplaceLast("gopher", "go").String()
println(v)
// #string gopher go

func (String) ReplacePrefix

func (s String) ReplacePrefix(old, repl string) String

ReplacePrefix replaces old with repl when old is a prefix of the string. Similar: ReplaceSuffix and TrimPrefix. @group Replace

Example: replace prefix

v := str.Of("prefix-value").ReplacePrefix("prefix-", "new-").String()
println(v)
// #string new-value

func (String) ReplaceSuffix

func (s String) ReplaceSuffix(old, repl string) String

ReplaceSuffix replaces old with repl when old is a suffix of the string. Similar: ReplacePrefix and TrimSuffix. @group Replace

Example: replace suffix

v := str.Of("file.old").ReplaceSuffix(".old", ".new").String()
println(v)
// #string file.new

func (String) Reverse

func (s String) Reverse() String

Reverse returns a rune-safe reversed string. @group Transform

Example: reverse

v := str.Of("naïve").Reverse().String()
println(v)
// #string evïan

func (String) RuneCount

func (s String) RuneCount() int

RuneCount returns the number of Unicode code points in the string. @group Length

Example: count runes instead of bytes

v := str.Of("gophers 🦫").RuneCount()
println(v)
// #int 9

func (String) Singular

func (s String) Singular() String

Singular returns a best-effort English singular form of the final identifier word. It handles common English forms and identifier boundaries without claiming to resolve every irregular or ambiguous noun. Similar: Plural. @group Pluralize

Example: singularize word

v := str.Of("people").Singular().String()
println(v)
// #string person

func (String) Slice

func (s String) Slice(start, end int) String

Slice returns the substring between rune offsets [start:end). Indices are clamped; if start >= end the result is empty. @group Substrings

Example: rune-safe slice

v := str.Of("naïve café").Slice(3, 7).String()
println(v)
// #string ve c

func (String) Slug

func (s String) Slug() String

Slug returns a lowercase Unicode slug separated by hyphens. Unicode letters and digits are preserved, while every other run is collapsed to one hyphen. Similar: Kebab. @group Slug

Example: build slug

v := str.Of("Go Forj Toolkit").Slug().String()
println(v)
// #string go-forj-toolkit

func (String) Snake

func (s String) Snake() String

Snake converts the string to snake_case. Similar: Kebab. @group Case

Example: snake case

v := str.Of("fooBar baz").Snake().String()
println(v)
// #string foo_bar_baz

func (String) Split

func (s String) Split(sep string) []string

Split splits the string by the given separator. @group Split

Example: split on comma

v := str.Of("a,b,c").Split(",")
fmt.Println(v)
// #[]string [a b c]

func (String) SplitWords

func (s String) SplitWords() []string

SplitWords splits the string into Unicode words, including camel case and acronym boundaries. Similar: FirstWord, LastWord, WordCount, and Words. @group Words

Example: split words

v := str.Of("one, two, three").SplitWords()
fmt.Println(v)
// #[]string [one two three]

func (String) String

func (s String) String() string

String returns the underlying raw string value. @group Fluent

Example: unwrap to plain string

v := str.Of("go").String()
println(v)
// #string go

func (String) SubstrReplace

func (s String) SubstrReplace(repl string, start, end int) String

SubstrReplace replaces the rune slice in [start:end) with repl. @group Substrings

Example: replace range

v := str.Of("naïve café").SubstrReplace("i", 2, 3).String()
println(v)
// #string naive café

func (String) Swap

func (s String) Swap(pairs map[string]string) String

Swap replaces multiple values using strings.Replacer built from a map. Similar: ReplaceArray. @group Replace

Example: swap map

pairs := map[string]string{"Gophers": "GoForj", "are": "is", "great": "fantastic"}
v := str.Of("Gophers are great!").Swap(pairs).String()
println(v)
// #string GoForj is fantastic!

func (String) Take

func (s String) Take(length int) String

Take returns the first length runes of the string (clamped). Similar: TakeLast and Limit. @group Substrings

Example: take head

v := str.Of("gophers").Take(3).String()
println(v)
// #string gop

func (String) TakeLast

func (s String) TakeLast(length int) String

TakeLast returns the last length runes of the string (clamped). Similar: Take. @group Substrings

Example: take tail

v := str.Of("gophers").TakeLast(4).String()
println(v)
// #string hers

func (String) Title

func (s String) Title() String

Title converts the string to title case (first letter of each word upper, rest lower) using Unicode rules. Similar: Headline. @group Case

Example: title case words

v := str.Of("a nice title uses the correct case").Title().String()
println(v)
// #string A Nice Title Uses The Correct Case

func (String) ToBase64

func (s String) ToBase64() String

ToBase64 encodes the string using standard Base64. Similar: FromBase64. @group Encoding

Example: base64 encode

v := str.Of("gopher").ToBase64().String()
println(v)
// #string Z29waGVy

func (String) ToLower

func (s String) ToLower() String

ToLower returns a lowercase copy of the string using Unicode rules. Similar: ToUpper and LcFirst. @group Case

Example: lowercase text

v := str.Of("GoLang").ToLower().String()
println(v)
// #string golang

func (String) ToUpper

func (s String) ToUpper() String

ToUpper returns an uppercase copy of the string using Unicode rules. Similar: ToLower and UcFirst. @group Case

Example: uppercase text

v := str.Of("GoLang").ToUpper().String()
println(v)
// #string GOLANG

func (String) Trim

func (s String) Trim() String

Trim removes leading and trailing Unicode whitespace. Similar: TrimLeft, TrimRight, and TrimChars. @group Cleanup

Example: trim whitespace

v := str.Of("  GoForj  ").Trim().String()
println(v)
// #string GoForj

func (String) TrimChars

func (s String) TrimChars(cutset string) String

TrimChars removes leading and trailing runes contained in cutset. Similar: Trim. @group Cleanup

Example: trim selected characters

v := str.Of("..GoForj!!").TrimChars(".!").String()
println(v)
// #string GoForj

func (String) TrimLeft

func (s String) TrimLeft() String

TrimLeft removes leading Unicode whitespace. Similar: Trim and TrimRight. @group Cleanup

Example: trim left

v := str.Of("  GoForj  ").TrimLeft().String()
println(v)
// #string GoForj\u0020\u0020

func (String) TrimPrefix

func (s String) TrimPrefix(prefix string) String

TrimPrefix removes prefix when it appears at the start of the string. Similar: TrimSuffix and EnsurePrefix. @group Affixes

Example: trim prefix

v := str.Of("https://goforj.dev").TrimPrefix("https://").String()
println(v)
// #string goforj.dev

func (String) TrimRight

func (s String) TrimRight() String

TrimRight removes trailing Unicode whitespace. Similar: Trim and TrimLeft. @group Cleanup

Example: trim right

v := str.Of("  GoForj  ").TrimRight().String()
println(v)
// #string \u0020\u0020GoForj

func (String) TrimSuffix

func (s String) TrimSuffix(suffix string) String

TrimSuffix removes suffix when it appears at the end of the string. Similar: TrimPrefix and EnsureSuffix. @group Affixes

Example: trim suffix

v := str.Of("file.txt").TrimSuffix(".txt").String()
println(v)
// #string file

func (String) UcFirst

func (s String) UcFirst() String

UcFirst returns the string with the first rune upper-cased. Similar: LcFirst and ToUpper. @group Case

Example: uppercase first rune

v := str.Of("gopher").UcFirst().String()
println(v)
// #string Gopher

func (String) Unwrap

func (s String) Unwrap(before, after string) String

Unwrap removes matching before and after strings if present. Similar: Wrap. @group Affixes

Example: unwrap string

v := str.Of(`"GoForj"`).Unwrap(`"`, `"`).String()
println(v)
// #string GoForj

func (String) WordCount

func (s String) WordCount() int

WordCount returns the number of detected words. Similar: SplitWords. @group Words

Example: count words

v := str.Of("Hello, world!").WordCount()
println(v)
// #int 2

func (String) Words

func (s String) Words(count int, suffix string) String

Words limits the string to count words, preserving the source through the selected word boundary and appending suffix if truncated. Similar: SplitWords and WrapWords. @group Words

Example: limit words

v := str.Of("Perfectly balanced, as all things should be.").Words(3, " >>>").String()
println(v)
// #string Perfectly balanced, as >>>

func (String) Wrap

func (s String) Wrap(before, after string) String

Wrap surrounds the string with before and after. Similar: Unwrap. @group Affixes

Example: wrap string

v := str.Of("GoForj").Wrap(`"`, `"`).String()
println(v)
// #string "GoForj"

func (String) WrapWords

func (s String) WrapWords(width int, breakStr string) String

WrapWords wraps the string to the given rune width on whitespace boundaries, using breakStr between lines without discarding punctuation. Similar: Words. @group Words

Example: wrap words

v := str.Of("The quick brown fox jumped over the lazy dog.").WrapWords(20, "\n").String()
println(v)
// #string The quick brown fox\njumped over the lazy\ndog.

Jump to

Keyboard shortcuts

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