Open History to see the last commit
1/**
2 * Works with TypeScript `string` values.
3 *
4 * This module exposes common string operations in a pipe-friendly style. The
5 * helpers cover checks, comparison, concatenation, trimming, casing, slicing,
6 * padding, replacement, normalization, safe character access, search helpers
7 * that return `Option`, and joining strings through a reducer.
8 *
9 * @since 2.0.0
10 */
11
12import type { NonEmptyArray } from "./Array.ts"
13import * as Equ from "./Equivalence.ts"
14import { dual } from "./Function.ts"
15import * as readonlyArray from "./internal/array.ts"
16import * as number from "./Number.ts"
17import * as Option from "./Option.ts"
18import * as order from "./Order.ts"
19import type * as Ordering from "./Ordering.ts"
20import type { Refinement } from "./Predicate.ts"
21import * as predicate from "./Predicate.ts"
22import * as Reducer from "./Reducer.ts"
23
24/**
25 * Exposes the global string constructor.
26 *
27 * **When to use**
28 *
29 * Use to access native JavaScript string coercion or constructor behavior from
30 * the Effect module namespace.
31 *
32 * **Gotchas**
33 *
34 * Calling `String(value)` returns a primitive string. Calling
35 * `new String(value)` creates a boxed `String` object.
36 *
37 * @see {@link isString} for checking whether a value is a primitive string
38 *
39 * @category constructors
40 * @since 4.0.0
41 */
42export const String = globalThis.String
43
44/**
45 * Checks whether a value is a `string`.
46 *
47 * **Example** (Checking for strings)
48 *
49 * ```ts
50 * import { String } from "effect"
51 * import * as assert from "node:assert"
52 *
53 * assert.deepStrictEqual(String.isString("a"), true)
54 * assert.deepStrictEqual(String.isString(1), false)
55 * ```
56 *
57 * @category guards
58 * @since 2.0.0
59 */
60export const isString: Refinement<unknown, string> = predicate.isString
61
62/**
63 * Provides an `Order` instance for comparing strings using lexicographic
64 * ordering.
65 *
66 * **Example** (Comparing strings lexicographically)
67 *
68 * ```ts
69 * import { String } from "effect"
70 *
71 * console.log(String.Order("apple", "banana")) // -1
72 * console.log(String.Order("banana", "apple")) // 1
73 * console.log(String.Order("apple", "apple")) // 0
74 * ```
75 *
76 * @category instances
77 * @since 2.0.0
78 */
79export const Order: order.Order<string> = order.String
80
81/**
82 * Provides an `Equivalence` instance for strings using strict equality (`===`).
83 *
84 * **Example** (Comparing strings for equality)
85 *
86 * ```ts
87 * import { String } from "effect"
88 *
89 * console.log(String.Equivalence("hello", "hello")) // true
90 * console.log(String.Equivalence("hello", "world")) // false
91 * ```
92 *
93 * @category instances
94 * @since 2.0.0
95 */
96export const Equivalence: Equ.Equivalence<string> = Equ.String
97
98/**
99 * Provides the empty string `""`.
100 *
101 * **When to use**
102 *
103 * Use when you need the canonical empty string value from the `String` module.
104 *
105 * **Example** (Referencing the empty string)
106 *
107 * ```ts
108 * import { String } from "effect"
109 *
110 * console.log(String.empty) // ""
111 * console.log(String.isEmpty(String.empty)) // true
112 * ```
113 *
114 * @category constants
115 * @since 2.0.0
116 */
117export const empty: "" = "" as const
118
119/**
120 * Concatenates two strings at the type level.
121 *
122 * **Example** (Concatenating string literal types)
123 *
124 * ```ts
125 * import type { String } from "effect"
126 *
127 * // Type-level concatenation
128 * type Result = String.Concat<"hello", "world"> // "helloworld"
129 * ```
130 *
131 * @category models
132 * @since 2.0.0
133 */
134export type Concat<A extends string, B extends string> = `${A}${B}`
135
136/**
137 * Concatenates two strings at runtime.
138 *
139 * **Example** (Concatenating strings)
140 *
141 * ```ts
142 * import { pipe, String } from "effect"
143 *
144 * const result1 = String.concat("hello", "world")
145 * console.log(result1) // "helloworld"
146 *
147 * const result2 = pipe("hello", String.concat("world"))
148 * console.log(result2) // "helloworld"
149 * ```
150 *
151 * @category combining
152 * @since 2.0.0
153 */
154export const concat: {
155 <B extends string>(that: B): <A extends string>(self: A) => Concat<A, B>
156 <A extends string, B extends string>(self: A, that: B): Concat<A, B>
157} = dual(2, (self: string, that: string): string => self + that)
158
159/**
160 * Converts a string to uppercase.
161 *
162 * **Example** (Converting strings to uppercase)
163 *
164 * ```ts
165 * import { pipe, String } from "effect"
166 * import * as assert from "node:assert"
167 *
168 * assert.deepStrictEqual(pipe("a", String.toUpperCase), "A")
169 * assert.deepStrictEqual(String.toUpperCase("hello"), "HELLO")
170 * ```
171 *
172 * @category transforming
173 * @since 2.0.0
174 */
175export const toUpperCase = <S extends string>(self: S): Uppercase<S> => self.toUpperCase() as Uppercase<S>
176
177/**
178 * Converts a string to lowercase.
179 *
180 * **Example** (Converting strings to lowercase)
181 *
182 * ```ts
183 * import { pipe, String } from "effect"
184 * import * as assert from "node:assert"
185 *
186 * assert.deepStrictEqual(pipe("A", String.toLowerCase), "a")
187 * assert.deepStrictEqual(String.toLowerCase("HELLO"), "hello")
188 * ```
189 *
190 * @category transforming
191 * @since 2.0.0
192 */
193export const toLowerCase = <T extends string>(self: T): Lowercase<T> => self.toLowerCase() as Lowercase<T>
194
195/**
196 * Capitalizes the first character of a string.
197 *
198 * **Example** (Capitalizing a string)
199 *
200 * ```ts
201 * import { pipe, String } from "effect"
202 * import * as assert from "node:assert"
203 *
204 * assert.deepStrictEqual(pipe("abc", String.capitalize), "Abc")
205 * assert.deepStrictEqual(String.capitalize("hello"), "Hello")
206 * ```
207 *
208 * @category transforming
209 * @since 2.0.0
210 */
211export const capitalize = <T extends string>(self: T): Capitalize<T> => {
212 if (self.length === 0) return self as Capitalize<T>
213
214 return (toUpperCase(self[0]) + self.slice(1)) as Capitalize<T>
215}
216
217/**
218 * Uncapitalizes the first character of a string.
219 *
220 * **Example** (Uncapitalizing a string)
221 *
222 * ```ts
223 * import { pipe, String } from "effect"
224 * import * as assert from "node:assert"
225 *
226 * assert.deepStrictEqual(pipe("ABC", String.uncapitalize), "aBC")
227 * assert.deepStrictEqual(String.uncapitalize("Hello"), "hello")
228 * ```
229 *
230 * @category transforming
231 * @since 2.0.0
232 */
233export const uncapitalize = <T extends string>(self: T): Uncapitalize<T> => {
234 if (self.length === 0) return self as Uncapitalize<T>
235
236 return (toLowerCase(self[0]) + self.slice(1)) as Uncapitalize<T>
237}
238
239/**
240 * Replaces matches in a string using `String.prototype.replace`.
241 *
242 * **Details**
243 *
244 * String search values and non-global regular expressions replace the first
245 * match; global regular expressions replace every match.
246 *
247 * **Example** (Replacing a substring)
248 *
249 * ```ts
250 * import { pipe, String } from "effect"
251 * import * as assert from "node:assert"
252 *
253 * assert.deepStrictEqual(pipe("abc", String.replace("b", "d")), "adc")
254 * assert.deepStrictEqual(
255 * pipe("hello world", String.replace("world", "Effect")),
256 * "hello Effect"
257 * )
258 * ```
259 *
260 * @category transforming
261 * @since 2.0.0
262 */
263export const replace = (searchValue: string | RegExp, replaceValue: string) => (self: string): string =>
264 self.replace(searchValue, replaceValue)
265
266/**
267 * Type-level representation of trimming whitespace from both ends of a string.
268 *
269 * **Example** (Trimming whitespace at the type level)
270 *
271 * ```ts
272 * import type { String } from "effect"
273 *
274 * type Result = String.Trim<" hello "> // "hello"
275 * ```
276 *
277 * @category models
278 * @since 2.0.0
279 */
280export type Trim<A extends string> = TrimEnd<TrimStart<A>>
281
282/**
283 * Removes whitespace from both ends of a string.
284 *
285 * **Example** (Trimming whitespace)
286 *
287 * ```ts
288 * import { String } from "effect"
289 * import * as assert from "node:assert"
290 *
291 * assert.deepStrictEqual(String.trim(" a "), "a")
292 * assert.deepStrictEqual(String.trim(" hello world "), "hello world")
293 * ```
294 *
295 * @category transforming
296 * @since 2.0.0
297 */
298export const trim = <A extends string>(self: A): Trim<A> => self.trim() as Trim<A>
299
300/**
301 * Type-level representation of trimming whitespace from the start of a string.
302 *
303 * **Example** (Trimming leading whitespace at the type level)
304 *
305 * ```ts
306 * import type { String } from "effect"
307 *
308 * type Result = String.TrimStart<" hello"> // "hello"
309 * ```
310 *
311 * @category models
312 * @since 2.0.0
313 */
314export type TrimStart<A extends string> = A extends `${" " | "\n" | "\t" | "\r"}${infer B}` ? TrimStart<B> : A
315
316/**
317 * Removes whitespace from the start of a string.
318 *
319 * **Example** (Trimming leading whitespace)
320 *
321 * ```ts
322 * import { String } from "effect"
323 * import * as assert from "node:assert"
324 *
325 * assert.deepStrictEqual(String.trimStart(" a "), "a ")
326 * assert.deepStrictEqual(String.trimStart(" hello world"), "hello world")
327 * ```
328 *
329 * @category transforming
330 * @since 2.0.0
331 */
332export const trimStart = <A extends string>(self: A): TrimStart<A> => self.trimStart() as TrimStart<A>
333
334/**
335 * Type-level representation of trimming whitespace from the end of a string.
336 *
337 * **Example** (Trimming trailing whitespace at the type level)
338 *
339 * ```ts
340 * import type { String } from "effect"
341 *
342 * type Result = String.TrimEnd<"hello "> // "hello"
343 * ```
344 *
345 * @category models
346 * @since 2.0.0
347 */
348export type TrimEnd<A extends string> = A extends `${infer B}${" " | "\n" | "\t" | "\r"}` ? TrimEnd<B> : A
349
350/**
351 * Removes whitespace from the end of a string.
352 *
353 * **Example** (Trimming trailing whitespace)
354 *
355 * ```ts
356 * import { String } from "effect"
357 * import * as assert from "node:assert"
358 *
359 * assert.deepStrictEqual(String.trimEnd(" a "), " a")
360 * assert.deepStrictEqual(String.trimEnd("hello world "), "hello world")
361 * ```
362 *
363 * @category transforming
364 * @since 2.0.0
365 */
366export const trimEnd = <A extends string>(self: A): TrimEnd<A> => self.trimEnd() as TrimEnd<A>
367
368/**
369 * Extracts a section of a string and returns it as a new string.
370 *
371 * **Example** (Slicing strings)
372 *
373 * ```ts
374 * import { pipe, String } from "effect"
375 * import * as assert from "node:assert"
376 *
377 * assert.deepStrictEqual(pipe("abcd", String.slice(1, 3)), "bc")
378 * assert.deepStrictEqual(pipe("hello world", String.slice(0, 5)), "hello")
379 * ```
380 *
381 * @category transforming
382 * @since 2.0.0
383 */
384export const slice = (start?: number, end?: number) => (self: string): string => self.slice(start, end)
385
386/**
387 * Checks whether a `string` is empty.
388 *
389 * **Example** (Checking for empty strings)
390 *
391 * ```ts
392 * import { String } from "effect"
393 * import * as assert from "node:assert"
394 *
395 * assert.deepStrictEqual(String.isEmpty(""), true)
396 * assert.deepStrictEqual(String.isEmpty("a"), false)
397 * ```
398 *
399 * @category predicates
400 * @since 2.0.0
401 */
402export const isEmpty = (self: string): self is "" => self.length === 0
403
404/**
405 * Checks whether a `string` is non-empty.
406 *
407 * **Example** (Checking for non-empty strings)
408 *
409 * ```ts
410 * import { String } from "effect"
411 * import * as assert from "node:assert"
412 *
413 * assert.deepStrictEqual(String.isNonEmpty(""), false)
414 * assert.deepStrictEqual(String.isNonEmpty("a"), true)
415 * ```
416 *
417 * @category guards
418 * @since 2.0.0
419 */
420export const isNonEmpty = (self: string): boolean => self.length > 0
421
422/**
423 * Returns the JavaScript string length, measured in UTF-16 code units.
424 *
425 * **Example** (Getting string length)
426 *
427 * ```ts
428 * import { String } from "effect"
429 * import * as assert from "node:assert"
430 *
431 * assert.deepStrictEqual(String.length("abc"), 3)
432 * ```
433 *
434 * @category getters
435 * @since 2.0.0
436 */
437export const length = (self: string): number => self.length
438
439/**
440 * Splits a string into an array of substrings using a separator.
441 *
442 * **Example** (Splitting strings)
443 *
444 * ```ts
445 * import { pipe, String } from "effect"
446 * import * as assert from "node:assert"
447 *
448 * assert.deepStrictEqual(pipe("abc", String.split("")), ["a", "b", "c"])
449 * assert.deepStrictEqual(pipe("", String.split("")), [""])
450 * assert.deepStrictEqual(String.split("hello,world", ","), ["hello", "world"])
451 * ```
452 *
453 * @category transforming
454 * @since 2.0.0
455 */
456export const split: {
457 (separator: string | RegExp): (self: string) => NonEmptyArray<string>
458 (self: string, separator: string | RegExp): NonEmptyArray<string>
459} = dual(2, (self: string, separator: string | RegExp): NonEmptyArray<string> => {
460 const out = self.split(separator)
461 return readonlyArray.isArrayNonEmpty(out) ? out : [self]
462})
463
464/**
465 * Returns `true` if `searchString` appears as a substring of `self`, at one or more positions that are
466 * greater than or equal to `position`; otherwise, returns `false`.
467 *
468 * **Example** (Checking for substrings)
469 *
470 * ```ts
471 * import { pipe, String } from "effect"
472 * import * as assert from "node:assert"
473 *
474 * assert.deepStrictEqual(pipe("hello world", String.includes("world")), true)
475 * assert.deepStrictEqual(pipe("hello world", String.includes("foo")), false)
476 * ```
477 *
478 * @category predicates
479 * @since 2.0.0
480 */
481export const includes = (searchString: string, position?: number) => (self: string): boolean =>
482 self.includes(searchString, position)
483
484/**
485 * Returns `true` if the string starts with the specified search string.
486 *
487 * **Example** (Checking string prefixes)
488 *
489 * ```ts
490 * import { pipe, String } from "effect"
491 * import * as assert from "node:assert"
492 *
493 * assert.deepStrictEqual(pipe("hello world", String.startsWith("hello")), true)
494 * assert.deepStrictEqual(pipe("hello world", String.startsWith("world")), false)
495 * ```
496 *
497 * @category predicates
498 * @since 2.0.0
499 */
500export const startsWith = (searchString: string, position?: number) => (self: string): boolean =>
501 self.startsWith(searchString, position)
502
503/**
504 * Returns `true` if the string ends with the specified search string.
505 *
506 * **Example** (Checking string suffixes)
507 *
508 * ```ts
509 * import { pipe, String } from "effect"
510 * import * as assert from "node:assert"
511 *
512 * assert.deepStrictEqual(pipe("hello world", String.endsWith("world")), true)
513 * assert.deepStrictEqual(pipe("hello world", String.endsWith("hello")), false)
514 * ```
515 *
516 * @category predicates
517 * @since 2.0.0
518 */
519export const endsWith = (searchString: string, position?: number) => (self: string): boolean =>
520 self.endsWith(searchString, position)
521
522/**
523 * Returns the character code at the specified index safely, or `None` if the index is out of bounds.
524 *
525 * **Example** (Reading character codes)
526 *
527 * ```ts
528 * import { String } from "effect"
529 *
530 * String.charCodeAt("abc", 1) // Option.some(98)
531 * String.charCodeAt("abc", 4) // Option.none()
532 * ```
533 *
534 * @category elements
535 * @since 2.0.0
536 */
537export const charCodeAt: {
538 (index: number): (self: string) => Option.Option<number>
539 (self: string, index: number): Option.Option<number>
540} = dual(
541 2,
542 (self: string, index: number): Option.Option<number> =>
543 Option.filter(Option.some(self.charCodeAt(index)), (charCode) => !isNaN(charCode))
544)
545
546/**
547 * Extracts characters from a string between two specified indices.
548 *
549 * **Example** (Extracting substrings)
550 *
551 * ```ts
552 * import { pipe, String } from "effect"
553 *
554 * pipe("abcd", String.substring(1)) // "bcd"
555 * pipe("abcd", String.substring(1, 3)) // "bc"
556 * ```
557 *
558 * @category transforming
559 * @since 2.0.0
560 */
561export const substring = (start: number, end?: number) => (self: string): string => self.substring(start, end)
562
563/**
564 * Returns the character at the specified relative index safely, or `None` if the index is out of bounds.
565 *
566 * **Example** (Accessing characters safely)
567 *
568 * ```ts
569 * import { pipe, String } from "effect"
570 *
571 * pipe("abc", String.at(1)) // Option.some("b")
572 * pipe("abc", String.at(4)) // Option.none()
573 * ```
574 *
575 * @category elements
576 * @since 2.0.0
577 */
578export const at: {
579 (index: number): (self: string) => Option.Option<string>
580 (self: string, index: number): Option.Option<string>
581} = dual(2, (self: string, index: number): Option.Option<string> => Option.fromUndefinedOr(self.at(index)))
582
583/**
584 * Returns the character at the specified non-negative index safely, or `None` if the index is out of bounds.
585 *
586 * **Example** (Reading characters safely)
587 *
588 * ```ts
589 * import { pipe, String } from "effect"
590 *
591 * pipe("abc", String.charAt(1)) // Option.some("b")
592 * pipe("abc", String.charAt(4)) // Option.none()
593 * ```
594 *
595 * @category elements
596 * @since 2.0.0
597 */
598export const charAt: {
599 (index: number): (self: string) => Option.Option<string>
600 (self: string, index: number): Option.Option<string>
601} = dual(
602 2,
603 (self: string, index: number): Option.Option<string> => Option.filter(Option.some(self.charAt(index)), isNonEmpty)
604)
605
606/**
607 * Returns the Unicode code point at the specified index safely, or `None` if the index is out of bounds.
608 *
609 * **Example** (Reading code points)
610 *
611 * ```ts
612 * import { pipe, String } from "effect"
613 *
614 * pipe("abc", String.codePointAt(1)) // Option.some(98)
615 * pipe("abc", String.codePointAt(10)) // Option.none()
616 * ```
617 *
618 * @category elements
619 * @since 2.0.0
620 */
621export const codePointAt: {
622 (index: number): (self: string) => Option.Option<number>
623 (self: string, index: number): Option.Option<number>
624} = dual(2, (self: string, index: number): Option.Option<number> => Option.fromUndefinedOr(self.codePointAt(index)))
625
626/**
627 * Returns the index of the first occurrence of a substring safely, or `None` if not found.
628 *
629 * **Example** (Finding the first substring index)
630 *
631 * ```ts
632 * import { pipe, String } from "effect"
633 *
634 * pipe("abbbc", String.indexOf("b")) // Option.some(1)
635 * pipe("abbbc", String.indexOf("z")) // Option.none()
636 * ```
637 *
638 * @category searching
639 * @since 2.0.0
640 */
641export const indexOf = (searchString: string) => (self: string): Option.Option<number> =>
642 Option.filter(Option.some(self.indexOf(searchString)), number.isGreaterThanOrEqualTo(0))
643
644/**
645 * Returns the index of the last occurrence of a substring safely, or `None` if not found.
646 *
647 * **Example** (Finding the last substring index)
648 *
649 * ```ts
650 * import { pipe, String } from "effect"
651 *
652 * pipe("abbbc", String.lastIndexOf("b")) // Option.some(3)
653 * pipe("abbbc", String.lastIndexOf("d")) // Option.none()
654 * ```
655 *
656 * @category searching
657 * @since 2.0.0
658 */
659export const lastIndexOf = (searchString: string) => (self: string): Option.Option<number> =>
660 Option.filter(Option.some(self.lastIndexOf(searchString)), number.isGreaterThanOrEqualTo(0))
661
662/**
663 * Computes locale-aware ordering for two strings, with optional locales and
664 * collator options, and returns the result as an `Ordering` (`-1`, `0`, or
665 * `1`).
666 *
667 * **Example** (Comparing strings by locale)
668 *
669 * ```ts
670 * import { pipe, String } from "effect"
671 * import * as assert from "node:assert"
672 *
673 * assert.deepStrictEqual(pipe("a", String.localeCompare("b")), -1)
674 * assert.deepStrictEqual(pipe("b", String.localeCompare("a")), 1)
675 * assert.deepStrictEqual(pipe("a", String.localeCompare("a")), 0)
676 * ```
677 *
678 * @category comparing
679 * @since 2.0.0
680 */
681export const localeCompare =
682 (that: string, locales?: Array<string>, options?: Intl.CollatorOptions) => (self: string): Ordering.Ordering =>
683 number.sign(self.localeCompare(that, locales, options))
684
685/**
686 * Matches a string against a pattern safely and returns `Option.some` with the match
687 * array, or `Option.none` when the pattern does not match.
688 *
689 * **Example** (Matching regular expressions)
690 *
691 * ```ts
692 * import { Option, pipe, String } from "effect"
693 *
694 * const match = pipe("hello", String.match(/l+/))
695 *
696 * if (Option.isSome(match)) {
697 * console.log(`${match.value[0]}@${match.value.index}`) // "ll@2"
698 * }
699 *
700 * console.log(Option.isNone(pipe("hello", String.match(/x/)))) // true
701 * ```
702 *
703 * @category searching
704 * @since 2.0.0
705 */
706export const match = (regExp: RegExp | string) => (self: string): Option.Option<RegExpMatchArray> =>
707 Option.fromNullOr(self.match(regExp))
708
709/**
710 * Returns an iterator over all regular expression matches in the string using
711 * native `String.prototype.matchAll` semantics.
712 *
713 * **Example** (Iterating regular expression matches)
714 *
715 * ```ts
716 * import { pipe, String } from "effect"
717 *
718 * const matches = pipe("hello world", String.matchAll(/l/g))
719 * console.log(
720 * Array.from(matches, (match) => `${match[0]}@${match.index}`).join(", ")
721 * ) // "l@2, l@3, l@9"
722 * ```
723 *
724 * @category searching
725 * @since 2.0.0
726 */
727export const matchAll = (regExp: RegExp) => (self: string): IterableIterator<RegExpMatchArray> => self.matchAll(regExp)
728
729/**
730 * Normalizes a string according to the specified Unicode normalization form.
731 *
732 * **Example** (Normalizing Unicode strings)
733 *
734 * ```ts
735 * import { pipe, String } from "effect"
736 * import * as assert from "node:assert"
737 *
738 * const str = "\u1E9B\u0323"
739 * assert.deepStrictEqual(pipe(str, String.normalize()), "\u1E9B\u0323")
740 * assert.deepStrictEqual(pipe(str, String.normalize("NFC")), "\u1E9B\u0323")
741 * assert.deepStrictEqual(pipe(str, String.normalize("NFD")), "\u017F\u0323\u0307")
742 * assert.deepStrictEqual(pipe(str, String.normalize("NFKC")), "\u1E69")
743 * assert.deepStrictEqual(
744 * pipe(str, String.normalize("NFKD")),
745 * "\u0073\u0323\u0307"
746 * )
747 * ```
748 *
749 * @category transforming
750 * @since 2.0.0
751 */
752export const normalize = (form?: "NFC" | "NFD" | "NFKC" | "NFKD") => (self: string): string => self.normalize(form)
753
754/**
755 * Pads the string from the end with a given fill string to a specified length.
756 *
757 * **Example** (Padding strings at the end)
758 *
759 * ```ts
760 * import { pipe, String } from "effect"
761 * import * as assert from "node:assert"
762 *
763 * assert.deepStrictEqual(pipe("a", String.padEnd(5)), "a ")
764 * assert.deepStrictEqual(pipe("a", String.padEnd(5, "_")), "a____")
765 * ```
766 *
767 * @category transforming
768 * @since 2.0.0
769 */
770export const padEnd = (maxLength: number, fillString?: string) => (self: string): string =>
771 self.padEnd(maxLength, fillString)
772
773/**
774 * Pads the string from the start with a given fill string to a specified length.
775 *
776 * **Example** (Padding strings at the start)
777 *
778 * ```ts
779 * import { pipe, String } from "effect"
780 * import * as assert from "node:assert"
781 *
782 * assert.deepStrictEqual(pipe("a", String.padStart(5)), " a")
783 * assert.deepStrictEqual(pipe("a", String.padStart(5, "_")), "____a")
784 * ```
785 *
786 * @category transforming
787 * @since 2.0.0
788 */
789export const padStart = (maxLength: number, fillString?: string) => (self: string): string =>
790 self.padStart(maxLength, fillString)
791
792/**
793 * Repeats the string the specified number of times.
794 *
795 * **Example** (Repeating strings)
796 *
797 * ```ts
798 * import { pipe, String } from "effect"
799 * import * as assert from "node:assert"
800 *
801 * assert.deepStrictEqual(pipe("a", String.repeat(5)), "aaaaa")
802 * assert.deepStrictEqual(pipe("hello", String.repeat(3)), "hellohellohello")
803 * ```
804 *
805 * @category transforming
806 * @since 2.0.0
807 */
808export const repeat = (count: number) => (self: string): string => self.repeat(count)
809
810/**
811 * Replaces all occurrences of a substring or pattern in a string.
812 *
813 * **Example** (Replacing all matches)
814 *
815 * ```ts
816 * import { pipe, String } from "effect"
817 * import * as assert from "node:assert"
818 *
819 * assert.deepStrictEqual(pipe("ababb", String.replaceAll("b", "c")), "acacc")
820 * assert.deepStrictEqual(pipe("ababb", String.replaceAll(/ba/g, "cc")), "accbb")
821 * ```
822 *
823 * @category transforming
824 * @since 2.0.0
825 */
826export const replaceAll = (searchValue: string | RegExp, replaceValue: string) => (self: string): string =>
827 self.replaceAll(searchValue, replaceValue)
828
829/**
830 * Returns the index of the first match for a string or regular expression safely, or
831 * `Option.none` when no match is found.
832 *
833 * **Example** (Searching strings)
834 *
835 * ```ts
836 * import { String } from "effect"
837 *
838 * String.search("ababb", "b") // Option.some(1)
839 * String.search("ababb", /abb/) // Option.some(2)
840 * String.search("ababb", "d") // Option.none()
841 * ```
842 *
843 * @category searching
844 * @since 2.0.0
845 */
846export const search: {
847 (regExp: RegExp | string): (self: string) => Option.Option<number>
848 (self: string, regExp: RegExp | string): Option.Option<number>
849} = dual(
850 2,
851 (self: string, regExp: RegExp | string): Option.Option<number> =>
852 Option.filter(Option.some(self.search(regExp)), number.isGreaterThanOrEqualTo(0))
853)
854
855/**
856 * Converts the string to lowercase according to the specified locale.
857 *
858 * **Example** (Lowercasing strings by locale)
859 *
860 * ```ts
861 * import { pipe, String } from "effect"
862 * import * as assert from "node:assert"
863 *
864 * const str = "\u0130"
865 * assert.deepStrictEqual(pipe(str, String.toLocaleLowerCase("tr")), "i")
866 * ```
867 *
868 * @category transforming
869 * @since 2.0.0
870 */
871export const toLocaleLowerCase = (locale?: string | Array<string>) => (self: string): string =>
872 self.toLocaleLowerCase(locale)
873
874/**
875 * Converts the string to uppercase according to the specified locale.
876 *
877 * **Example** (Uppercasing strings by locale)
878 *
879 * ```ts
880 * import { pipe, String } from "effect"
881 * import * as assert from "node:assert"
882 *
883 * const str = "i\u0307"
884 * assert.deepStrictEqual(pipe(str, String.toLocaleUpperCase("lt-LT")), "I")
885 * ```
886 *
887 * @category transforming
888 * @since 2.0.0
889 */
890export const toLocaleUpperCase = (locale?: string | Array<string>) => (self: string): string =>
891 self.toLocaleUpperCase(locale)
892
893/**
894 * Keeps the specified number of characters from the start of a string.
895 *
896 * **Details**
897 *
898 * If `n` is larger than the available number of characters, the string will
899 * be returned whole.
900 *
901 * If `n` is not a positive number, an empty string will be returned.
902 *
903 * If `n` is a float, it will be rounded down to the nearest integer.
904 *
905 * **Example** (Taking characters from the start)
906 *
907 * ```ts
908 * import { String } from "effect"
909 * import * as assert from "node:assert"
910 *
911 * assert.deepStrictEqual(String.takeLeft("Hello World", 5), "Hello")
912 * ```
913 *
914 * @category transforming
915 * @since 2.0.0
916 */
917export const takeLeft: {
918 (n: number): (self: string) => string
919 (self: string, n: number): string
920} = dual(2, (self: string, n: number): string => self.slice(0, Math.max(n, 0)))
921
922/**
923 * Keeps the specified number of characters from the end of a string.
924 *
925 * **Details**
926 *
927 * If `n` is larger than the available number of characters, the string will
928 * be returned whole.
929 *
930 * If `n` is not a positive number, an empty string will be returned.
931 *
932 * If `n` is a float, it will be rounded down to the nearest integer.
933 *
934 * **Example** (Taking characters from the end)
935 *
936 * ```ts
937 * import { String } from "effect"
938 * import * as assert from "node:assert"
939 *
940 * assert.deepStrictEqual(String.takeRight("Hello World", 5), "World")
941 * ```
942 *
943 * @category transforming
944 * @since 2.0.0
945 */
946export const takeRight: {
947 (n: number): (self: string) => string
948 (self: string, n: number): string
949} = dual(
950 2,
951 (self: string, n: number): string => self.slice(Math.max(0, self.length - Math.floor(n)), Infinity)
952)
953
954const CR = 0x0d
955const LF = 0x0a
956
957/**
958 * Returns an `IterableIterator` which yields each line contained within the
959 * string, trimming off the trailing newline character.
960 *
961 * **Example** (Iterating lines without separators)
962 *
963 * ```ts
964 * import { String } from "effect"
965 *
966 * const lines = String.linesIterator("hello\nworld\n")
967 * console.log(Array.from(lines)) // ["hello", "world"]
968 * ```
969 *
970 * @category splitting
971 * @since 2.0.0
972 */
973export const linesIterator = (self: string): LinesIterator => linesSeparated(self, true)
974
975/**
976 * Returns an `IterableIterator` which yields each line contained within the
977 * string as well as the trailing newline character.
978 *
979 * **Example** (Iterating lines with separators)
980 *
981 * ```ts
982 * import { String } from "effect"
983 *
984 * const lines = String.linesWithSeparators("hello\nworld\n")
985 * console.log(Array.from(lines)) // ["hello\n", "world\n"]
986 * ```
987 *
988 * @category splitting
989 * @since 2.0.0
990 */
991export const linesWithSeparators = (s: string): LinesIterator => linesSeparated(s, false)
992
993/**
994 * Strips a leading margin prefix from every line using the supplied margin
995 * character.
996 *
997 * **Example** (Stripping custom margins)
998 *
999 * ```ts
1000 * import { String } from "effect"
1001 *
1002 * const text = " |hello\n |world"
1003 * const result = String.stripMarginWith(text, "|")
1004 * console.log(result) // "hello\nworld"
1005 * ```
1006 *
1007 * @category transforming
1008 * @since 2.0.0
1009 */
1010export const stripMarginWith: {
1011 (marginChar: string): (self: string) => string
1012 (self: string, marginChar: string): string
1013} = dual(2, (self: string, marginChar: string): string => {
1014 let out = ""
1015
1016 for (const line of linesWithSeparators(self)) {
1017 let index = 0
1018
1019 while (index < line.length && line.charAt(index) <= " ") {
1020 index = index + 1
1021 }
1022
1023 const stripped = index < line.length && line.charAt(index) === marginChar
1024 ? line.substring(index + 1)
1025 : line
1026
1027 out = out + stripped
1028 }
1029
1030 return out
1031})
1032
1033/**
1034 * Strips a leading `|` margin prefix from every line.
1035 *
1036 * **Example** (Stripping pipe margins)
1037 *
1038 * ```ts
1039 * import { String } from "effect"
1040 *
1041 * const text = " |hello\n |world"
1042 * const result = String.stripMargin(text)
1043 * console.log(result) // "hello\nworld"
1044 * ```
1045 *
1046 * @category transforming
1047 * @since 2.0.0
1048 */
1049export const stripMargin = (self: string): string => stripMarginWith(self, "|")
1050
1051/**
1052 * Converts a snake_case string to camelCase.
1053 *
1054 * **Example** (Converting snake_case to camelCase)
1055 *
1056 * ```ts
1057 * import { String } from "effect"
1058 *
1059 * console.log(String.snakeToCamel("hello_world")) // "helloWorld"
1060 * console.log(String.snakeToCamel("foo_bar_baz")) // "fooBarBaz"
1061 * ```
1062 *
1063 * @category transforming
1064 * @since 2.0.0
1065 */
1066export const snakeToCamel = (self: string): string => {
1067 let str = self[0]
1068 for (let i = 1; i < self.length; i++) {
1069 str += self[i] === "_" ? self[++i].toUpperCase() : self[i]
1070 }
1071 return str
1072}
1073
1074/**
1075 * Converts a snake_case string to PascalCase.
1076 *
1077 * **Example** (Converting snake_case to PascalCase)
1078 *
1079 * ```ts
1080 * import { String } from "effect"
1081 *
1082 * console.log(String.snakeToPascal("hello_world")) // "HelloWorld"
1083 * console.log(String.snakeToPascal("foo_bar_baz")) // "FooBarBaz"
1084 * ```
1085 *
1086 * @category transforming
1087 * @since 2.0.0
1088 */
1089export const snakeToPascal = (self: string): string => {
1090 let str = self[0].toUpperCase()
1091 for (let i = 1; i < self.length; i++) {
1092 str += self[i] === "_" ? self[++i].toUpperCase() : self[i]
1093 }
1094 return str
1095}
1096
1097/**
1098 * Converts a snake_case string to kebab-case.
1099 *
1100 * **Example** (Converting snake_case to kebab-case)
1101 *
1102 * ```ts
1103 * import { String } from "effect"
1104 *
1105 * console.log(String.snakeToKebab("hello_world")) // "hello-world"
1106 * console.log(String.snakeToKebab("foo_bar_baz")) // "foo-bar-baz"
1107 * ```
1108 *
1109 * @category transforming
1110 * @since 2.0.0
1111 */
1112export const snakeToKebab = (self: string): string => self.replace(/_/g, "-")
1113
1114/**
1115 * Converts a camelCase string to snake_case.
1116 *
1117 * **Example** (Converting camelCase to snake_case)
1118 *
1119 * ```ts
1120 * import { String } from "effect"
1121 *
1122 * console.log(String.camelToSnake("helloWorld")) // "hello_world"
1123 * console.log(String.camelToSnake("fooBarBaz")) // "foo_bar_baz"
1124 * ```
1125 *
1126 * @category transforming
1127 * @since 2.0.0
1128 */
1129export const camelToSnake = (self: string): string => self.replace(/([A-Z])/g, "_$1").toLowerCase()
1130
1131/**
1132 * Converts a PascalCase string to snake_case.
1133 *
1134 * **Example** (Converting PascalCase to snake_case)
1135 *
1136 * ```ts
1137 * import { String } from "effect"
1138 *
1139 * console.log(String.pascalToSnake("HelloWorld")) // "hello_world"
1140 * console.log(String.pascalToSnake("FooBarBaz")) // "foo_bar_baz"
1141 * ```
1142 *
1143 * @category transforming
1144 * @since 2.0.0
1145 */
1146export const pascalToSnake = (self: string): string =>
1147 (self.slice(0, 1) + self.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase()
1148
1149/**
1150 * Converts a kebab-case string to snake_case.
1151 *
1152 * **Example** (Converting kebab-case to snake_case)
1153 *
1154 * ```ts
1155 * import { String } from "effect"
1156 *
1157 * console.log(String.kebabToSnake("hello-world")) // "hello_world"
1158 * console.log(String.kebabToSnake("foo-bar-baz")) // "foo_bar_baz"
1159 * ```
1160 *
1161 * @category transforming
1162 * @since 2.0.0
1163 */
1164export const kebabToSnake = (self: string): string => self.replace(/-/g, "_")
1165
1166class LinesIterator implements IterableIterator<string> {
1167 private index: number
1168 private readonly length: number
1169 readonly s: string
1170 readonly stripped: boolean
1171
1172 constructor(
1173 s: string,
1174 stripped: boolean = false
1175 ) {
1176 this.s = s
1177 this.stripped = stripped
1178 this.index = 0
1179 this.length = s.length
1180 }
1181
1182 next(): IteratorResult<string> {
1183 if (this.done) {
1184 return { done: true, value: undefined }
1185 }
1186 const start = this.index
1187 while (!this.done && !isLineBreak(this.s[this.index]!)) {
1188 this.index = this.index + 1
1189 }
1190 let end = this.index
1191 if (!this.done) {
1192 const char = this.s[this.index]!
1193 this.index = this.index + 1
1194 if (!this.done && isLineBreak2(char, this.s[this.index]!)) {
1195 this.index = this.index + 1
1196 }
1197 if (!this.stripped) {
1198 end = this.index
1199 }
1200 }
1201 return { done: false, value: this.s.substring(start, end) }
1202 }
1203
1204 [Symbol.iterator](): IterableIterator<string> {
1205 return new LinesIterator(this.s, this.stripped)
1206 }
1207
1208 private get done(): boolean {
1209 return this.index >= this.length
1210 }
1211}
1212
1213/**
1214 * Checks whether the provided character is a line break character (i.e. either `"\r"`
1215 * or `"\n"`).
1216 */
1217const isLineBreak = (char: string): boolean => {
1218 const code = char.charCodeAt(0)
1219 return code === CR || code === LF
1220}
1221
1222/**
1223 * Checks whether the provided characters combine to form a carriage return/line-feed
1224 * (i.e. `"\r\n"`).
1225 */
1226const isLineBreak2 = (char0: string, char1: string): boolean => char0.charCodeAt(0) === CR && char1.charCodeAt(0) === LF
1227
1228const linesSeparated = (self: string, stripped: boolean): LinesIterator => new LinesIterator(self, stripped)
1229
1230/**
1231 * Normalizes a string by splitting it into word parts, transforming each part,
1232 * and joining the parts with a configurable delimiter.
1233 *
1234 * **When to use**
1235 *
1236 * Use when you need custom word-case output with a delimiter or part transform
1237 * that the fixed case helpers do not provide.
1238 *
1239 * @see {@link pascalCase} for fixed PascalCase output
1240 * @see {@link camelCase} for fixed lower-initial camelCase output
1241 * @see {@link constantCase} for fixed uppercase underscore-separated output
1242 * @see {@link kebabCase} for fixed lowercase hyphen-separated output
1243 * @see {@link snakeCase} for fixed lowercase underscore-separated output
1244 *
1245 * @category transforming
1246 * @since 4.0.0
1247 */
1248export const noCase: {
1249 (options?: {
1250 readonly splitRegExp?: RegExp | ReadonlyArray<RegExp> | undefined
1251 readonly stripRegExp?: RegExp | ReadonlyArray<RegExp> | undefined
1252 readonly delimiter?: string | undefined
1253 readonly transform?: (part: string, index: number, parts: ReadonlyArray<string>) => string
1254 }): (self: string) => string
1255 (self: string, options?: {
1256 readonly splitRegExp?: RegExp | ReadonlyArray<RegExp> | undefined
1257 readonly stripRegExp?: RegExp | ReadonlyArray<RegExp> | undefined
1258 readonly delimiter?: string | undefined
1259 readonly transform?: (part: string, index: number, parts: ReadonlyArray<string>) => string
1260 }): string
1261} = dual((args) => typeof args[0] === "string", (input: string, options?: {
1262 readonly splitRegExp?: RegExp | ReadonlyArray<RegExp> | undefined
1263 readonly stripRegExp?: RegExp | ReadonlyArray<RegExp> | undefined
1264 readonly delimiter?: string | undefined
1265 readonly transform?: (part: string, index: number, parts: ReadonlyArray<string>) => string
1266}): string => {
1267 const delimiter = options?.delimiter ?? " "
1268 const transform = options?.transform ?? toLowerCase
1269 return normalizeCase(input, SPLIT_REGEXP, STRIP_REGEXP, delimiter, transform)
1270})
1271
1272const normalizeCase = (
1273 input: string,
1274 splitRegExp: ReadonlyArray<RegExp>,
1275 stripRegExp: RegExp,
1276 delimiter: string,
1277 transform: (part: string, index: number, parts: ReadonlyArray<string>) => string
1278): string => {
1279 let result = input
1280 for (const regexp of splitRegExp) {
1281 result = result.replace(regexp, "$1\0$2")
1282 }
1283 result = result.replace(stripRegExp, "\0")
1284 let start = 0
1285 let end = result.length
1286 // Trim the delimiter from around the output string.
1287 while (result.charAt(start) === "\0") {
1288 start++
1289 }
1290 while (result.charAt(end - 1) === "\0") {
1291 end--
1292 }
1293
1294 // Transform each token independently.
1295 return result.slice(start, end).split("\0").map(transform).join(delimiter)
1296}
1297
1298// Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case")
1299// and digit boundaries ("camel2case" -> "camel 2 case").
1300const SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g, /([A-Z])([0-9])/gi, /([0-9])([A-Z])/gi]
1301
1302// Config paths preserve digit groups such as "v2" while still supporting camel case.
1303const CONFIG_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g]
1304
1305// Remove all non-word characters.
1306const STRIP_REGEXP = /[^A-Z0-9]+/gi
1307
1308const pascalCaseTransform = (input: string): string => {
1309 const firstChar = input.charAt(0)
1310 const lowerChars = input.substring(1).toLowerCase()
1311 return `${firstChar.toUpperCase()}${lowerChars}`
1312}
1313
1314/**
1315 * Converts a string to PascalCase.
1316 *
1317 * **When to use**
1318 *
1319 * Use to normalize strings from spaces, separators, or camel/Pascal word
1320 * boundaries into PascalCase.
1321 *
1322 * @see {@link camelCase} for lower-initial camelCase output
1323 * @see {@link noCase} for configurable delimiters and part transforms
1324 * @see {@link snakeToPascal} for converting known snake_case input only
1325 *
1326 * @category transforming
1327 * @since 4.0.0
1328 */
1329export const pascalCase: (self: string) => string = noCase({
1330 delimiter: "",
1331 transform: pascalCaseTransform
1332})
1333
1334const camelCaseTransform = (input: string, index: number): string =>
1335 index === 0
1336 ? input.toLowerCase()
1337 : pascalCaseTransform(input)
1338
1339/**
1340 * Converts a string to camelCase.
1341 *
1342 * **When to use**
1343 *
1344 * Use to normalize mixed word separators or existing PascalCase/camelCase text
1345 * into lower-initial camelCase identifiers.
1346 *
1347 * @see {@link noCase} for configurable delimiters and part transforms
1348 * @see {@link pascalCase} for upper-initial PascalCase output
1349 * @see {@link snakeCase} for lowercase underscore-separated output
1350 * @see {@link kebabCase} for lowercase hyphen-separated output
1351 * @see {@link constantCase} for uppercase underscore-separated output
1352 *
1353 * @category transforming
1354 * @since 4.0.0
1355 */
1356export const camelCase: (self: string) => string = noCase({
1357 delimiter: "",
1358 transform: camelCaseTransform
1359})
1360
1361/**
1362 * Converts a string to CONSTANT_CASE (uppercase with underscores).
1363 *
1364 * **When to use**
1365 *
1366 * Use to normalize words from mixed input formats into uppercase,
1367 * underscore-separated identifiers.
1368 *
1369 * @see {@link snakeCase} for lowercase underscore-separated output
1370 * @see {@link kebabCase} for lowercase hyphen-separated output
1371 * @see {@link camelCase} for lower-initial camelCase output
1372 * @see {@link pascalCase} for upper-initial PascalCase output
1373 * @see {@link configCase} for configuration key casing that preserves numeric word groups
1374 * @see {@link noCase} for configurable delimiters and part transforms
1375 *
1376 * @category transforming
1377 * @since 4.0.0
1378 */
1379export const constantCase: (self: string) => string = noCase({
1380 delimiter: "_",
1381 transform: toUpperCase
1382})
1383
1384/**
1385 * Converts a string to CONFIG_CASE (uppercase with underscores) for
1386 * configuration keys.
1387 *
1388 * **When to use**
1389 *
1390 * Use to normalize configuration path segments into environment-variable-like
1391 * keys while preserving numeric word groups such as `v2`.
1392 *
1393 * **Details**
1394 *
1395 * Unlike {@link constantCase}, digit-letter boundaries are not split. For
1396 * example, `"api-v2 xml"` becomes `"API_V2_XML"`.
1397 *
1398 * @see {@link constantCase} for standard uppercase underscore-separated output
1399 * @category transforming
1400 * @since 4.0.0
1401 */
1402export const configCase: (self: string) => string = (self) =>
1403 normalizeCase(self, CONFIG_SPLIT_REGEXP, STRIP_REGEXP, "_", toUpperCase)
1404
1405/**
1406 * Converts a string to kebab-case (lowercase with hyphens).
1407 *
1408 * **When to use**
1409 *
1410 * Use to normalize free-form labels, identifiers, or keys into lowercase
1411 * hyphen-separated text.
1412 *
1413 * @see {@link noCase} for configurable delimiters and part transforms
1414 * @see {@link snakeCase} for lowercase underscore-separated output
1415 * @see {@link constantCase} for uppercase underscore-separated output
1416 * @see {@link camelCase} for lower-initial camelCase output
1417 * @see {@link pascalCase} for upper-initial PascalCase output
1418 *
1419 * @category transforming
1420 * @since 4.0.0
1421 */
1422export const kebabCase: (self: string) => string = noCase({
1423 delimiter: "-"
1424})
1425
1426/**
1427 * Converts a string to snake_case (lowercase with underscores).
1428 *
1429 * **When to use**
1430 *
1431 * Use to normalize mixed-case or separator-delimited text into lowercase words
1432 * joined with underscores.
1433 *
1434 * @see {@link noCase} for configurable lower-level normalization
1435 * @see {@link kebabCase} for lowercase hyphen-separated output
1436 * @see {@link constantCase} for uppercase underscore-separated output
1437 *
1438 * @category transforming
1439 * @since 4.0.0
1440 */
1441export const snakeCase: (self: string) => string = noCase({
1442 delimiter: "_"
1443})
1444
1445/**
1446 * Reducer for concatenating `string`s.
1447 *
1448 * **When to use**
1449 *
1450 * Use to concatenate many strings through APIs that consume a `Reducer`.
1451 *
1452 * **Details**
1453 *
1454 * The reducer starts from `""`, so combining an empty collection returns `""`.
1455 *
1456 * @see {@link concat} for concatenating two strings directly
1457 *
1458 * @category combining
1459 * @since 4.0.0
1460 */
1461export const ReducerConcat: Reducer.Reducer<string> = Reducer.make((a, b) => a + b, "")