@halvaradop/ts-utility-types/strings

Utilities for manipulating and analyzing string types in TypeScript. These types allow you to trim, join, search, replace, capitalize, and analyze strings at the type level.

import type * as Strings from "@halvaradop/ts-utility-types/strings"

Table of Contents

TrimLeft<Str extends string>

Removes whitespace from the start of a string type.

// Expected: "hello world  "
type TrimmedLeft = TrimLeft<"  hello world  ">

TrimRight<Str extends string>

Removes whitespace from the end of a string type.

// Expected: "hello world"
type TrimmedRight = TrimRight<"hello world  ">

Trim<Str extends string>

Removes whitespace from both ends of a string type.

// Expected: "hello world"
type Trimmed = Trim<"  hello world  ">

Capitalize<Str extends string, FirstWord = true>

Capitalizes the first letter of a word and lowercases the rest.

// Expected: "Hello world"
type Capitalized = Capitalize<"hello world">

Join<Array extends unknown[], Separator extends number | string>

Joins the values of a tuple into a string, using the given separator.

// Expected: "a-p-p-l-e"
type Join1 = Join<["a", "p", "p", "l", "e"], "-">

// Expected: "Hello World"
type Join2 = Join<["Hello", "World"], " ">

StartsWith<Str extends string, Match extends string>

Checks if a string type starts with the given value.

// Expected: false
type Test1 = StartsWith<"abc", "ac">

// Expected: true
type Test2 = StartsWith<"abc", "ab">

DropChar<Str extends string, Match extends string>

Removes all occurrences of a character from a string type.

// Expected: "butterfly!"
type Test2 = DropChar<" b u t t e r f l y ! ", " ">

EndsWith<Str extends string, Match extends string>

Checks if a string type ends with the given value.

// Expected: true
type Test1 = EndsWith<"abc", "bc">

// Expected: false
type Test2 = EndsWith<"abc", "ac">

LengthOfString<Str extends string>

Returns the length of a string type.

// Expected: 3
type Length2 = LengthOfString<"foo">

// Expected: 6
type Length6 = LengthOfString<"foobar">

IndexOfString<Str extends string, Match extends string>

Returns the index of the first occurrence of a character in the string. Returns -1 if not found.

// Expected: 2
type Index = IndexOfString<"foo", "o">

// Expected: -1
type NotFound = IndexOfString<"foo", "z">