Back to Lo

Core Substring

docs/data/core-substring.md

1.53.0964 B
Original Source

Returns a substring starting at the given offset with the specified length. Supports negative offsets; out-of-bounds are clamped. Operates on Unicode runes (characters) and is optimized for zero allocations.

go
// Basic usage
result := lo.Substring("hello", 2, 3)
// result: "llo"

// Negative offset - counts from end
result = lo.Substring("hello", -4, 3)
// result: "ell"

// Length longer than string - clamped to available characters
result = lo.Substring("hello", 1, 10)
// result: "ello" (only 4 characters available from position 1)

// Zero length - returns empty string
result = lo.Substring("hello", 1, 0)
// result: ""

// Offset beyond string length - returns empty string
result = lo.Substring("hello", 10, 3)
// result: ""

// With Unicode strings (rune-aware)
result = lo.Substring("héllo", 1, 3)
// result: "él"

// Negative offset with negative values clamped
result = lo.Substring("hello", -10, 3)
// result: "hel" (offset clamped to 0)