Go Back

Refer: Medium - Replace

Describe

Implement Replace<S, From, To> which replace the string From with To once in the given string S.

For example

code snippetCopytypescript
type replaced = Replace<'types are fun!', 'fun', 'awesome'> // expected to be 'types are awesome!'

Test Cases

code snippetCopytypescript
import { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect<Equal<Replace<'foobar', 'bar', 'foo'>, 'foofoo'>>, Expect<Equal<Replace<'foobarbar', 'bar', 'foo'>, 'foofoobar'>>, Expect<Equal<Replace<'foobarbar', '', 'foo'>, 'foobarbar'>>, Expect<Equal<Replace<'foobarbar', 'bra', 'foo'>, 'foobarbar'>>, Expect<Equal<Replace<'', '', ''>, ''>>, ]

Solution

code snippetCopytypescript
type Replace<S extends string, From extends string, To extends string> = From extends '' ? S : S extends `${infer P}${From}${infer K}` ? `${P}${To}${K}` : S