1 | type ReplaceOptions = {
|
2 | all?: boolean;
|
3 | };
|
4 |
|
5 | /**
|
6 | Represents a string with some or all matches replaced by a replacement.
|
7 |
|
8 | Use-case:
|
9 | - `snake-case-path` to `dotted.path.notation`
|
10 | - Changing date/time format: `01-08-2042` → `01/08/2042`
|
11 | - Manipulation of type properties, for example, removal of prefixes
|
12 |
|
13 | @example
|
14 | ```
|
15 | import {Replace} from 'type-fest';
|
16 |
|
17 | declare function replace<
|
18 | Input extends string,
|
19 | Search extends string,
|
20 | Replacement extends string
|
21 | >(
|
22 | input: Input,
|
23 | search: Search,
|
24 | replacement: Replacement
|
25 | ): Replace<Input, Search, Replacement>;
|
26 |
|
27 | declare function replaceAll<
|
28 | Input extends string,
|
29 | Search extends string,
|
30 | Replacement extends string
|
31 | >(
|
32 | input: Input,
|
33 | search: Search,
|
34 | replacement: Replacement
|
35 | ): Replace<Input, Search, Replacement, {all: true}>;
|
36 |
|
37 | // The return type is the exact string literal, not just `string`.
|
38 |
|
39 | replace('hello ?', '?', '🦄');
|
40 | //=> 'hello 🦄'
|
41 |
|
42 | replace('hello ??', '?', '❓');
|
43 | //=> 'hello ❓?'
|
44 |
|
45 | replaceAll('10:42:00', ':', '-');
|
46 | //=> '10-42-00'
|
47 |
|
48 | replaceAll('__userName__', '__', '');
|
49 | //=> 'userName'
|
50 |
|
51 | replaceAll('My Cool Title', ' ', '');
|
52 | //=> 'MyCoolTitle'
|
53 | ```
|
54 |
|
55 | @category String
|
56 | @category Template literal
|
57 | */
|
58 | export type Replace<
|
59 | Input extends string,
|
60 | Search extends string,
|
61 | Replacement extends string,
|
62 | Options extends ReplaceOptions = {},
|
63 | > = Input extends `${infer Head}${Search}${infer Tail}`
|
64 | ? Options['all'] extends true
|
65 | ? `${Head}${Replacement}${Replace<Tail, Search, Replacement, Options>}`
|
66 | : `${Head}${Replacement}${Tail}`
|
67 | : Input;
|