str

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package str ports the "String" category of the npm lodash library to Go. It provides the familiar lodash string helpers: the case converters (CamelCase, KebabCase, SnakeCase, StartCase, LowerCase, UpperCase, Capitalize, UpperFirst, LowerFirst), the word splitter Words, the padding and repeating helpers (Pad, PadStart, PadEnd, Repeat), the trimming family (Trim, TrimStart, TrimEnd), predicates (StartsWith, EndsWith), HTML entity handling (Escape, Unescape), diacritic folding (Deburr), plus Truncate, Replace and a JavaScript-style ParseInt. Every function operates on plain Go strings and depends only on the standard library.

Use this package when you are porting front-end JavaScript that relied on lodash string utilities, or whenever you want their concise, well-defined behavior in Go: turning arbitrary identifiers or user input into a consistent case (slugs, config keys, display labels), normalizing accented text for search or comparison, padding and truncating strings for fixed-width output, or escaping text for safe inclusion in HTML. The helpers are Unicode-aware where it matters — lengths, slicing and padding are measured in runes rather than bytes — so multi-byte input is handled the way lodash measures strings by code point.

The heart of the package is Words, and understanding it explains most of the rest. Words scans the input rune by rune and emits maximal runs of letters or digits, treating any non-alphanumeric rune as a separator; it also splits on case boundaries so that camelCase, PascalCase, snake_case, kebab-case and spaced text all decompose into the same word list. A run of upper-case letters is kept together as an acronym, except that a trailing upper-case letter immediately followed by a lower-case letter starts the next word, so "XMLHttpTest" splits into "XML", "Http", "Test". The case converters are all built on a shared compounder that first runs Deburr and strips apostrophes, then splits with Words, then rejoins the words with a per-converter combiner (CamelCase lower-cases each word and upper-cases the first letter of all but the first; KebabCase and SnakeCase lower-case and join with "-" or "_"; StartCase upper-cases each word's first letter and joins with spaces).

Edge cases follow lodash. Empty input yields an empty result from every function, and the case converters collapse leading, trailing and repeated separators (so "--foo-bar--" and "__FOO_BAR__" both reduce cleanly). The pad helpers return the string unchanged when it already meets or exceeds the requested length, default to a single space when the chars argument is empty, and truncate the padding pattern to fit exactly. The trim helpers strip Unicode whitespace by default, or exactly the set of runes in chars when one is given. StartsWith and EndsWith interpret their position argument in runes, with EndsWith treating a negative position as the end of the string. ParseInt mirrors JavaScript's parseInt: it honours leading whitespace and a sign, auto-detects a "0x" hex prefix when the radix is 0, and stops at the first character that is not a valid digit for the radix (returning 0 when nothing parses). Deburr covers the Latin-1 Supplement and the more common Latin Extended-A letters and drops combining diacritical marks (U+0300..U+036F).

Parity with Node's lodash is high for the covered functions, with a few deliberate boundaries. Deburr's mapping table is a representative subset of lodash's full Latin transliteration rather than an exhaustive copy, so exotic code points may pass through unchanged. Escape and Unescape handle the same five HTML characters lodash does (& < > " '); they are not general-purpose HTML sanitizers. This package covers the pure string utilities and omits lodash template compilation and the various pluralization/inflection helpers that were never part of lodash's string category.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CamelCase

func CamelCase(s string) string

CamelCase converts string to camel case.

CamelCase("Foo Bar")   => "fooBar"
CamelCase("--foo-bar--") => "fooBar"
CamelCase("__FOO_BAR__") => "fooBar"
Example

ExampleCamelCase converts arbitrary text to camel case. It first splits the input into words, then lower-cases each word and upper-cases the first letter of every word after the first, joining them with no separator. Leading, trailing and repeated separators are collapsed, so surrounding dashes or underscores disappear. Fully upper-cased input is normalized down to camel case as well. All three inputs here therefore produce the same result.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.CamelCase("Foo Bar"))
	fmt.Println(str.CamelCase("--foo-bar--"))
	fmt.Println(str.CamelCase("__FOO_BAR__"))
}
Output:
fooBar
fooBar
fooBar

func Capitalize

func Capitalize(s string) string

Capitalize converts the first character of string to upper case and the remaining to lower case.

Capitalize("FRED") => "Fred"

func Chars added in v0.4.0

func Chars(s string) []string

Chars splits s into a slice of its Unicode characters (runes as strings), so Chars("a€b") is ["a", "€", "b"]. It mirrors lodash's toArray/split("") on a string.

func Deburr

func Deburr(s string) string

Deburr converts the Latin-1 Supplement and common Latin Extended-A accented letters in string to their basic Latin equivalents and removes combining diacritical marks (U+0300..U+036F).

Deburr("déjà vu") => "deja vu"
Example

ExampleDeburr folds accented Latin letters to their basic ASCII equivalents and removes combining diacritical marks. It covers the Latin-1 Supplement and the more common Latin Extended-A letters, which is enough for most Western European text. This is useful for normalizing text before case-insensitive search or slug generation. Characters outside the mapped set pass through unchanged. Here an accented French phrase is reduced to plain ASCII.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.Deburr("déjà vu"))
}
Output:
deja vu

func EndsWith

func EndsWith(s, target string, position int) bool

EndsWith reports whether string ends with the given target, testing up to the supplied position (in runes). A negative position is treated as the end of the string.

EndsWith("abc", "c", -1) => true
EndsWith("abc", "b", 2)  => true

func Escape

func Escape(s string) string

Escape converts the characters "&", "<", ">", '"' and "'" in string to their corresponding HTML entities.

Escape("fred, barney, & pebbles") => "fred, barney, &amp; pebbles"
Example

ExampleEscape converts the five HTML-significant characters (&, <, >, " and ') into their corresponding HTML entities. It is meant for interpolating untrusted text into HTML content, not for general-purpose sanitization. Only those five characters are affected; all other text is left as is. The inverse operation is provided by Unescape. Here an ampersand is converted to &amp;.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.Escape("fred, barney, & pebbles"))
}
Output:
fred, barney, &amp; pebbles

func KebabCase

func KebabCase(s string) string

KebabCase converts string to kebab case.

KebabCase("Foo Bar")   => "foo-bar"
KebabCase("fooBar")    => "foo-bar"
KebabCase("__FOO_BAR__") => "foo-bar"
Example

ExampleKebabCase converts text to kebab case, lower-casing each word and joining them with hyphens. It is a common way to derive URL slugs or CSS class names from a label. Because it is built on the same word splitter as the other converters, it also breaks apart camelCase and acronym-heavy identifiers. Here "XMLHttpRequest" becomes three lower-cased, hyphen-joined words. Separators in the input are normalized away.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.KebabCase("fooBar"))
	fmt.Println(str.KebabCase("XMLHttpRequest"))
}
Output:
foo-bar
xml-http-request

func LowerCase

func LowerCase(s string) string

LowerCase converts string, as space separated words, to lower case.

LowerCase("--Foo-Bar--") => "foo bar"
LowerCase("fooBar")      => "foo bar"

func LowerFirst

func LowerFirst(s string) string

LowerFirst converts the first character of string to lower case, leaving the remainder untouched.

LowerFirst("Fred") => "fred"
LowerFirst("FRED") => "fRED"

func Pad

func Pad(s string, length int, chars string) string

Pad pads string on the left and right sides if it is shorter than length. Padding characters are truncated if they cannot be evenly divided by length.

Pad("abc", 8, "_-") => "_-abc_-_"
Pad("abc", 3, " ")  => "abc"
Example

ExamplePad centers a string within a target width by adding padding on both sides. When the string is already at least as long as the target it is returned unchanged. The padding characters are taken from the chars argument and repeated, then truncated so the total length is exactly right. When the two sides cannot be split evenly the extra padding goes on the right. Here "abc" is padded to width 8 using the two-character pattern "_-".

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.Pad("abc", 8, "_-"))
}
Output:
_-abc_-_

func PadEnd

func PadEnd(s string, length int, chars string) string

PadEnd pads string on the right side if it is shorter than length.

PadEnd("abc", 6, " ")  => "abc   "
PadEnd("abc", 6, "_-") => "abc_-_"

func PadStart

func PadStart(s string, length int, chars string) string

PadStart pads string on the left side if it is shorter than length.

PadStart("abc", 6, " ")  => "   abc"
PadStart("abc", 6, "_-") => "_-_abc"

func ParseInt

func ParseInt(s string, radix int) int

ParseInt converts string to an integer of the specified radix. A radix of 0 selects base 16 for values prefixed with "0x"/"0X" and base 10 otherwise, mirroring JavaScript's parseInt. Leading whitespace and a sign are honoured; parsing stops at the first character that is not a valid digit.

ParseInt("08", 10)  => 8
ParseInt("0x1A", 0) => 26
ParseInt("42px", 10) => 42
Example

ExampleParseInt parses a string into an integer, mirroring JavaScript's parseInt. A radix of 10 reads a decimal number, tolerating a leading zero. A radix of 0 auto-detects a "0x" prefix and parses as hexadecimal. Parsing stops at the first character that is not a valid digit for the radix, so trailing text like a unit suffix is ignored rather than causing an error. The three cases show decimal, hex auto-detection and trailing-text handling.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.ParseInt("08", 10))
	fmt.Println(str.ParseInt("0x1A", 0))
	fmt.Println(str.ParseInt("42px", 10))
}
Output:
8
26
42

func Repeat

func Repeat(s string, n int) string

Repeat repeats the given string n times. A non-positive n yields "".

Repeat("*", 3) => "***"
Repeat("abc", 0) => ""

func Replace

func Replace(s, old, replacement string) string

Replace replaces the first occurrence of old in string with replacement, matching JavaScript's String.prototype.replace when called with a string pattern.

Replace("Hi Fred", "Fred", "Barney") => "Hi Barney"

func SnakeCase

func SnakeCase(s string) string

SnakeCase converts string to snake case.

SnakeCase("Foo Bar")   => "foo_bar"
SnakeCase("fooBar")    => "foo_bar"
SnakeCase("--FOO-BAR--") => "foo_bar"
Example

ExampleSnakeCase converts text to snake case, lower-casing each word and joining them with underscores. Like the other converters it splits camelCase, kebab-case and spaced input uniformly. This form is common for database column names and environment-variable-like keys. Leading and trailing separators in the input are discarded. The example converts a spaced label.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.SnakeCase("Foo Bar"))
	fmt.Println(str.SnakeCase("fooBar"))
}
Output:
foo_bar
foo_bar

func Split added in v0.4.0

func Split(s, separator string, limit int) []string

Split splits s around each instance of separator. When limit is negative all substrings are returned; when limit is zero the result is empty; otherwise at most limit substrings are returned, with the final one holding the unsplit remainder — matching lodash.split's limit semantics for whole-separator splitting.

func StartCase

func StartCase(s string) string

StartCase converts string to start case, capitalizing the first letter of every word while preserving the remaining letters of each word.

StartCase("--foo-bar--") => "Foo Bar"
StartCase("fooBar")      => "Foo Bar"
StartCase("XMLHttp")     => "XML Http"
Example

ExampleStartCase converts text to start case, upper-casing the first letter of every word and joining the words with single spaces. Unlike Capitalize it preserves the remaining letters of each word rather than lower-casing them, which is why an acronym like "XML" stays upper-cased. It is well suited to producing human-readable titles from identifiers. Surrounding separators are removed during splitting. The two examples show a slug and an acronym.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.StartCase("--foo-bar--"))
	fmt.Println(str.StartCase("XMLHttp"))
}
Output:
Foo Bar
XML Http

func StartsWith

func StartsWith(s, target string, position int) bool

StartsWith reports whether string begins with the given target, testing from the supplied position (in runes).

StartsWith("abc", "a", 0) => true
StartsWith("abc", "b", 1) => true

func ToLower added in v0.4.0

func ToLower(s string) string

ToLower returns s with all Unicode letters mapped to lower case. Unlike LowerCase, it does not split the string into words; it mirrors lodash.toLower.

func ToUpper added in v0.4.0

func ToUpper(s string) string

ToUpper returns s with all Unicode letters mapped to upper case. Unlike UpperCase, it does not split the string into words; it mirrors lodash.toUpper.

func Trim

func Trim(s string, chars string) string

Trim removes leading and trailing characters (whitespace by default, or any of the runes in chars when provided) from string.

Trim("  abc  ", "")     => "abc"
Trim("-_-abc-_-", "_-") => "abc"

func TrimEnd

func TrimEnd(s string, chars string) string

TrimEnd removes trailing characters (whitespace by default, or any of the runes in chars when provided) from string.

TrimEnd("  abc  ", "")     => "  abc"
TrimEnd("-_-abc-_-", "_-") => "-_-abc"

func TrimStart

func TrimStart(s string, chars string) string

TrimStart removes leading characters (whitespace by default, or any of the runes in chars when provided) from string.

TrimStart("  abc  ", "")     => "abc  "
TrimStart("-_-abc-_-", "_-") => "abc-_-"

func Truncate

func Truncate(s string, opts TruncateOptions) string

Truncate truncates string if it is longer than the requested length. The last characters of the truncated string are replaced with the omission string (default "..."). Options mirror lodash's _.truncate.

Truncate("hi-diddly-ho there, neighborino", TruncateOptions{})
  => "hi-diddly-ho there, neig..."
Example

ExampleTruncate shortens a string that exceeds a maximum length, replacing the tail with an omission marker. With a zero-value options struct the length defaults to 30 and the omission defaults to "...". The omission is counted against the length budget, so the retained text plus the marker fit within the limit. Strings already within the limit are returned unchanged. This example uses the defaults on a long string.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Println(str.Truncate("hi-diddly-ho there, neighborino", str.TruncateOptions{}))
}
Output:
hi-diddly-ho there, neighbo...

func Unescape

func Unescape(s string) string

Unescape is the inverse of Escape; it converts the HTML entities "&amp;", "&lt;", "&gt;", "&quot;" and "&#39;" in string back to their characters.

Unescape("fred, barney, &amp; pebbles") => "fred, barney, & pebbles"

func UpperCase

func UpperCase(s string) string

UpperCase converts string, as space separated words, to upper case.

UpperCase("--foo-bar--") => "FOO BAR"
UpperCase("fooBar")      => "FOO BAR"

func UpperFirst

func UpperFirst(s string) string

UpperFirst converts the first character of string to upper case, leaving the remainder untouched.

UpperFirst("fred") => "Fred"
UpperFirst("FRED") => "FRED"

func Words

func Words(s string) []string

Words splits string into an array of its words. It understands camelCase, snake_case, kebab-case, spaced text, digits and upper-case acronyms.

Words("fooBar")      => ["foo", "Bar"]
Words("XMLHttpTest") => ["XML", "Http", "Test"]
Words("foo_bar-baz") => ["foo", "bar", "baz"]
Example

ExampleWords shows the word splitter that underpins the case converters. It scans the input and emits maximal runs of letters or digits, treating every other rune as a separator. It also splits on case boundaries, so camelCase input decomposes into its component words. A run of upper-case letters is kept together as an acronym, except that the final upper-case letter attaches to a following lower-case word, which is why "XMLHttpTest" splits into three words. The %q verb quotes each element so the boundaries are visible.

package main

import (
	"fmt"

	"github.com/malcolmston/express/lodash/str"
)

func main() {
	fmt.Printf("%q\n", str.Words("fooBar"))
	fmt.Printf("%q\n", str.Words("XMLHttpTest"))
}
Output:
["foo" "Bar"]
["XML" "Http" "Test"]

Types

type TruncateOptions

type TruncateOptions struct {
	// Length is the maximum rune length of the result including Omission. A
	// value <= 0 falls back to the lodash default of 30.
	Length int
	// Omission is the string appended to indicate truncation. An empty value
	// falls back to "...".
	Omission string
	// Separator, when non-empty, causes truncation to occur at the last
	// occurrence of this literal substring within the retained text.
	Separator string
	// SeparatorRegexp, when non-nil, causes truncation at the last match of the
	// pattern within the retained text and takes precedence over Separator.
	SeparatorRegexp *regexp.Regexp
}

TruncateOptions configures Truncate. A zero Length falls back to the lodash default of 30 and an empty Omission falls back to "...". Separator, when set, causes truncation to happen at the last separator match within the retained text; SeparatorRegexp takes precedence over Separator when non-nil.

Jump to

Keyboard shortcuts

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